[Leetcode] Missing Number
2016-10-01 01:14
204 查看
Given an array containing n distinct numbers taken from
find the one that is missing from the array.
For example,
Given nums =
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
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
相关文章推荐
- leetcode 268: Missing Number
- [LeetCode] Missing Number
- LeetCode编程练习 - Missing Number学习心得 4000
- leetcode——268——Missing Number
- 【Leetcode】Missing Number
- leetcode---Missing Number---位
- Leetcode_Missing Number
- 【LeetCode】268 Missing Number (java实现)
- leetcode 268 : Missing Number
- LeetCode 268 Missing Number
- Leetcode: Missing Number
- Leetcode--No.268--Missing Number
- leetcode268: Missing Number
- LeetCode--Missing Number(查找丢失的整数)Python
- 《leetCode》:Missing Number
- Leetcode -- Missing Number
- LeetCode(268) Missing Number
- leetcode——Missing Number
- LeetCode-Missing Number
- Leetcode 268 Missing Number