leetcode 268. 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:
Output: 2
Example 2:
Input:
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;
for(int i = 0 ; i< nums.length; i++){
re]++;
}
for(int i = 0; i< re.length ; i++){
if(re == 0) return i;
}
return max+1;
}
}
class Solution {
public int missingNumber(int[] nums) {
int sum = 0, max =nums;
for(int i:nums){
sum += i;
if(i > max) max =i;
}
int total = nums.length * (nums.length+1)/2;
return total - sum;
}
}
页:
[1]