Created
February 3, 2017 06:25
-
-
Save ruoguluo/7f2fec9e4f5b0ffa64fdf87965923387 to your computer and use it in GitHub Desktop.
Find the duplicated number in an array of length N
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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