Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1
代码语言:javascript复制Input: [3,0,1]
Output: 2
Example 2
代码语言:javascript复制Input: [9,6,4,2,3,5,7,0,1]
Output: 8
我的版本:
代码语言:javascript复制package leetCode;
import java.util.Arrays;
/**
* Created by luoluo on 2018/1/27.
先进行快排,然后在判断
*/
public class MissingNumber {
public static void main(String[] args) {
int[] a = {3,0,1};
missingNumber(a);
System.out.println(Arrays.toString(a));
}
public static int missingNumber(int[] nums) {
int n = nums.length;
sort(nums, 0, n-1);
if(nums[0] != n ){
return n;
}else if(nums[nums.length-1] !=0){
return 0;
}
for (int i = 0; i < nums.length-1; i ) {
if(nums[i]-nums[i 1]!=1){
return nums[i]-1;
}
}
return 0;
}
public static void sort(int[] nums ,int bg,int end){
if (bg >= end) {
return;
}
int partition = partition(nums, bg, end);
sort(nums, bg, partition - 1);
sort(nums, partition 1, end);
}
public static int partition(int[] nums,int bg, int end){
int l = nums[bg];
int j = bg;
for (int i = bg 1; i <= end; i ) {
if(nums[i]>l){
j ;
swap(nums, i, j);
}
}
swap(nums, j, bg);
return j;
}
public static void swap(int[] nums ,int a ,int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}
大神的版本:
代码语言:javascript复制public static int missingNumber(int[] nums) {
int sum = nums.length;
for (int i = 0; i < nums.length; i )
sum = i - nums[i];
return sum;
}