LeetCode解題報告(448)

Question:Find All Numbers Disappeared in an Array
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搞錯了題目的意思。以爲是找到數組最大和最小的元素,查找之間不存在的元素。
但是實際上,題目是假設nums數組的長度爲len,返回的就是nums中從1到len中不存在的數。

搞清題目的要求後,採用最簡單的桶排序,複雜度能夠達到O(n)。
題目比較Easy,大家看代碼應該能看懂。但是需要注意的是:數組的長度需要提前進行判斷。否則會直接報錯。

public class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> ans = new ArrayList<>();
        if(nums.length==0 || nums==null){
            return ans;
        }
       int[] info = new int[nums.length];//創建一個數組用來進行桶排序
       for(int i=0;i<nums.length;i++){
           info[nums[i]-1]+=1;//如果出現數字i,則對應的info[i]加1
       }
       for(int i=0;i<nums.length;i++){
           if(info[i]==0){
               ans.add(i+1);//如果info[i]爲0,就是i不存在nums數組中。
           }
       }
       return ans;
    }
}

提交結果:
測試結果

延伸閱讀:桶排序

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章