|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- 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?
复制代码
- class Solution {
- public int missingNumber(int[] nums) {
- int max = Integer.MIN_VALUE;
- for(int i:nums){
-
- if(i > max) max = i;
- }
-
- int[] re = new int[max+1];
-
- for(int i = 0 ; i< nums.length; i++){
-
- re[nums[i]]++;
- }
-
- for(int i = 0; i< re.length ; i++){
-
- if(re[i] == 0) return i;
- }
-
- return max+1;
-
- }
- }
复制代码
- class Solution {
- public int missingNumber(int[] nums) {
-
- int sum = 0, max =nums[0];
- for(int i:nums){
-
- sum += i;
- if(i > max) max =i;
- }
-
- int total = nums.length * (nums.length+1)/2;
-
- return total - sum;
-
- }
- }
复制代码 |
|