您的位置:首页 > 其它

[Leetcode] Missing Number

2016-10-01 01:14 204 查看
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?
public class Solution {
private void swap(int[] nums, int pos1, int pos2) {
int tmp = nums[pos1];
nums[pos1] = nums[pos2];
nums[pos2] = tmp;
}
public int missing
4000
Number(int[] nums) {
int i = 0;
while(i < nums.length) {
if(i == nums[i] || nums[i] >= nums.length) {
i++;
}
else {
swap(nums, i, nums[i]);
}
}

for(i = 0; i < nums.length; i++) {
if(i != nums[i]) {
return i;
}
}
return nums.length;
}
}

Better solution by sum and subtraction
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: