Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
给定一个数组,找到缺失的那个数。
解答
import java.util.Arrays;
/**
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
*/
public class MissingNumber {
public static int missingNumber(int[] nums) {
/**
* 方法一:先把数组排序,再遍历数组,相邻两个数相减,如果差值不为1,这两个数中间有缺失
*/
//排序
Arrays.sort(nums);
//对数组首尾进行判断
if (nums[nums.length-1]!=nums.length) return nums.length;
if (nums[0]!=0) return 0;
for (int i=0;i<nums.length-1;i++){
if (nums[i+1]-nums[i]!=1) return nums[i]+1;
}
//方法二;先求和再相减,对nums.length求和
int result=nums.length*(nums.length+1)/2;
for (int i=0;i<nums.length;i++){
result-=nums[i];
}
return result;
//return -1;
}
public static void main(String[] args) {
int[] arr={3,0,1,2,5,6};
System.out.println(missingNumber(arr));
}
}