268. Missing Number
Posted apanda009
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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. For example, Given nums = [0, 1, 3] return 2. Note: Your algorithm should run in linear runtime complexity.
Could you implement it using only constant extra space complexity?
1.XOR public int missingNumber(int[] nums) { //xor int res = nums.length; for(int i=0; i<nums.length; i++){ res ^= i; res ^= nums[i]; } return res; } 2.SUM public int missingNumber(int[] nums) { //sum int len = nums.length; int sum = (0+len)*(len+1)/2; for(int i=0; i<len; i++) sum-=nums[i]; return sum; } 3.Binary Search public int missingNumber(int[] nums) { //binary search Arrays.sort(nums); int left = 0, right = nums.length, mid= (left + right)/2; while(left<right){ mid = (left + right)/2; if(nums[mid]>mid) right = mid; else left = mid+1; } return left; }
以上是关于268. Missing Number的主要内容,如果未能解决你的问题,请参考以下文章