LeetCode: 448. Find All Numbers Disappeared in an Array

来源:互联网 发布:kj90数据采集传输协议 编辑:程序博客网 时间:2024/05/25 18:12

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:[4,3,2,7,8,2,3,1]Output:[5,6]

Subscribe to see which companies asked this question.

一开始我的代码是:


class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        sort(nums.begin(),nums.end());        vector<int> res;        int length = nums.size();        for (int i = 0;i<length;i++)        {            if(nums[i+1]-nums[i]>2)            {                for(int j =1;j<nums[i+1]-nums[i];j++)                {                    int temp = nums[i]+j;                    res.push_back(temp);                }            }        }        return res;    }};
当我看到以下结果,我就知道自己没有好好了解这么n,到底是什么意思

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for i in xrange(len(nums)):
            index = abs(nums[i]) - 1
            nums[index] = - abs(nums[index])


        return [i + 1 for i in range(len(nums)) if nums[i] > 0]

Submission Result: Wrong Answer More Details 

Input:[1,1]
Output:[]
Expected:[2]



AC:
class Solution(object):    def findDisappearedNumbers(self, nums):        """        :type nums: List[int]        :rtype: List[int]        """        for i in xrange(len(nums)):            index = abs(nums[i]) - 1            nums[index] = - abs(nums[index])        return [i + 1 for i in range(len(nums)) if nums[i] > 0]




阅读全文
0 0