Skip to content

Instantly share code, notes, and snippets.

@ruoguluo
Created February 3, 2017 06:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruoguluo/7f2fec9e4f5b0ffa64fdf87965923387 to your computer and use it in GitHub Desktop.
Save ruoguluo/7f2fec9e4f5b0ffa64fdf87965923387 to your computer and use it in GitHub Desktop.
Find the duplicated number in an array of length N
public class FindDuplicate {
public static void main(String[] args) {
FindDuplicate fd = new FindDuplicate();
int[] nums = new int[]{1, 2, 3, 4, 5, 6, 1};
assert (fd.find(nums) == 1);
nums = new int[]{1, 2, 3, 4, 5, 6, 1};
assert (fd.find(nums) == 1);
nums = new int[]{2, 2, 3, 4, 5, 6, 1};
assert (fd.find(nums) == 2);
nums = new int[]{3, 2, 3, 4, 5, 6, 1};
assert (fd.find(nums) == 3);
nums = new int[]{4, 2, 3, 4, 5, 6, 1};
assert (fd.find(nums) == 4);
nums = new int[]{5, 2, 3, 4, 5, 6, 1};
assert (fd.find(nums) == 5);
nums = new int[]{6, 2, 3, 4, 5, 6, 1};
assert (fd.find(nums) == 6);
}
private int find(int[] nums) {
int start = 1;
int end = nums.length - 1;
while (start != end) {
int mid = start + ((end - start) / 2);
int count = 0;
int countMid = 0;
for (int num : nums) {
if (num > mid && num <= end) count += 1;
if (num == mid) countMid += 1;
}
if (countMid > 1) return mid;
if (count > (end - mid)) start = mid + 1;
else end = mid - 1;
}
return start;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment