196.Find the Missing Number
作者:
博瑜 | 来源:发表于
2017-08-02 23:51 被阅读0次public class Solution {
/**
* @param nums: an array of integers
* @return: an integer
*/
public int findMissing(int[] nums) {
// write your code here
Arrays.sort(nums);
int N = nums.length;
int start = 0;
int end = N - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] > mid) end = mid;
else start = mid;
}
if (nums[start] != start) return start;
else if (nums[end] != end) return end;
else return end + 1;
}
}
public class Solution {
/**
* @param nums: an array of integers
* @return: an integer
*/
public int findMissing(int[] nums) {
// write your code here
int N = nums.length;
int sum = 0;
for (int i = 0; i < N; i++) {
sum += nums[i];
}
return N * (N + 1) /2 - sum;
}
}
public class Solution {
/**
* @param nums: an array of integers
* @return: an integer
*/
public int findMissing(int[] nums) {
// write your code here
Arrays.sort(nums);
int N = nums.length;
int start = 0;
int end = N - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] > mid) end = mid;
else start = mid;
}
if (nums[start] != start) return start;
else if (nums[end] != end) return end;
else return end + 1;
}
}
本文标题:196.Find the Missing Number
本文链接:https://www.haomeiwen.com/subject/ihlulxtx.html
网友评论