268. Missing Number
Posted 一日一更
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.
Example 1
Input: [3,0,1] Output: 2
Example 2
Input: [9,6,4,2,3,5,7,0,1] Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
解题思路:
在最后添加一个-1值,对数组从0-N对每个数字进行归位,最后数字不符合的就是丢失的那个数字。
- class Solution {
- public:
- int missingNumber(vector<int>& nums) {
- if(nums.size()==0) return 0;
- nums.push_back(-1);
- for(int i=0;i<nums.size();i++){
- int temp;
- int index=nums[i];
- if(index==-1) break;
- while(1){
- temp = nums[index];
- nums[index] = index;
- if(temp == nums[index] || temp ==-1) break;
- index = temp;
- }
- }
- for(int i=0;i<=nums.size();i++)
- if(nums[i]!=i) return i;
- }
- };
以上是关于268. Missing Number的主要内容,如果未能解决你的问题,请参考以下文章