287. Find the Duplicate Number

题目:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.

解答:
1.Binary Tree

public int findDuplicate(int[] nums) {
int start = 1, end = nums.length - 1;
while (start + 1 countEnd ? start : end;
}
2.LinkedList Find the starting point of circle

public int findDuplicate(int[] nums) {
int n = nums.length;

int slow = nums[0];
int fast = nums[nums[0]];
while (slow != fast) {
    slow = nums[slow];
    fast = nums[nums[fast]];
}

fast = 0;
while (slow != fast) {
    slow = nums[slow];
    fast = nums[fast];
}
return slow;

}

关键字:java, leetcode, nums, int


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部