287. Find the Duplicate Number
Find the Duplicate Number
Solution
public class Solution {
public int findDuplicate(int[] nums) {
if (nums == null || nums.length == 0) return -1;
int n = nums.length - 1;
int low = 1;
int high = n;
while (low <= high) {
int middle = low + (high - low) / 2;
int count = count(nums, middle);
if (count <= middle) {
low = middle+1;
} else {
high = middle-1;
}
}
return low;
}
private int count(int[] nums, int target) {
int sum = 0;
for (int num : nums) {
if (num <= target) {
sum++;
}
}
return sum;
}
}Last updated