0到n的sum减去已经存在的就是missing number
1 //Old 2 class Solution { 3 public int missingNumber(int[] nums) { 4 int max = nums.length; 5 List<Integer> A = new ArrayList<Integer>(); 6 for(int i = 0; i <= max; i++) { 7 A.add(i); 8 } 9 for(int j = 0; j < nums.length; j++) { 10 A.set(nums[j], -1); 11 } 12 for(Integer a : A) { 13 if( a != -1) 14 return a; 15 } 16 return 0; 17 } 18 } 19 20 21 22 23 //New 100% 24 25 class Solution { 26 public int missingNumber(int[] nums) { 27 int n = nums.length; 28 int sum = (1 + n)* n / 2; 29 for(int a : nums) { 30 sum -= a; 31 } 32 return sum; 33 34 } 35 }
原文地址:https://www.cnblogs.com/goPanama/p/9399007.html
时间: 2024-10-08 15:47:31