标签:missing nbsp 随机 blog rom 个数 example ken gnu
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
随机从0到size()选取了n个数,其中只有一个丢失了(显然的)
方法一
1 int missingNumber(vector<int>& nums) { 2 int res = 0; 3 for (int i = 1; i <= nums.size(); i++) 4 res =res ^ i ^ nums[i-1]; 5 return res; 6 }
方法二
1 public int missingNumber(int[] nums) { 2 if (nums.length == 0) return 0; 3 if (nums.length == 1 ) return (nums[0]+1)%2; 4 Arrays.sort(nums); 5 for (int i=0;i<nums.length-1;i++) 6 { 7 if (nums[i]+1 != nums[i+1]) return nums[i]+1; 8 } 9 if(nums[0] > 0) return 0; 10 else return nums[nums.length-1] + 1; 11 }
方法二
1 int missingNumber(vector<int>& nums) { 2 int sum = 0; 3 for(int num: nums) 4 sum += num; 5 int n = nums.size(); 6 return (n * (n + 1))/ 2 - sum; 7 }
标签:missing nbsp 随机 blog rom 个数 example ken gnu
原文地址:http://www.cnblogs.com/wzj4858/p/7669843.html