1. 程式人生 > >448. Find All Numbers Disappeared in an Array(python+cpp)

448. Find All Numbers Disappeared in an Array(python+cpp)

題目:

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]

解釋: 題目要求顯而易見。 剛開始想法是吧nums變成set(不變成set會超時)然後遍歷一遍[1,len(nums)]求出答案,但是還是太慢。

python程式碼: 比較慢的:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        return list(
set(range(1,len(nums)+1))-set(nums))

比較快的:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        result=[]
        _set=set(nums)
        for i in range(1,len(nums)+1):
            if i not in _set:
result.append(i) return result

c++程式碼:

#include <set>
using namespace std;
class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> result;
        set<int> _set(nums.begin(),nums.end());
        for (int i =1;i<=nums.size();i++)
        {
            if (_set.count(i)==0)
                result.push_back(i);
        }
       return result; 
    }
};

不需要額外空間的解法: c++程式碼:

#include <set>
using namespace std;
class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> result;
        //用負號標記,如果本該儲存在這個位置的數字是存在的,且當前的數字是正的,則變成負數
        //最後返回正數的index+1
        int _len=nums.size();
        for(int i=0;i<_len;i++)
        {
            int index=abs(nums[i])-1;
            if (nums[index]>0)
                nums[index]=-nums[index]; 
        }
        for(int i=0;i<_len;i++)
        {
            if (nums[i]>0)
                result.push_back(i+1);
        }
        return result;
    }
};

總結: 不需要額外空間的解法的技巧還是很神奇的。