LeetCode | 448. 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:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]


我自己做的相當笨的方法,遍歷套遍歷,非常笨。代碼如下:

public class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        Arrays.sort(nums);
        List<Integer> list = new ArrayList<Integer>();
        int flag = 0;
        for(int i = 1; i <= nums.length; i++) {
            while(true) {
                if(i == nums[flag]) {
                    if(flag < nums.length - 1) flag++;
                    break;
                }
                if(i < nums[flag] || i > nums[nums.length - 1]) {
                    list.add(i);
                    break;
                }
                flag++;
            }
        }
        return list;
    }
}

看到discuss裏面的奇妙思路又跪了,簡單解釋下:
思路是這樣的,數組的每個位置經歷一次正負號的標記,標記後,如果該位置的值仍是正數,則說明其未被標記過,即該位置下標+1的對應數在數組中不曾出現。
標記的方法是遍歷原數組中的每個值,每個值-1後,代表的是1到n排序後的下標,把對應下標上的數組值置爲負數,證明其出現過。否則沒有。

public List<Integer> findDisappearedNumbers(int[] nums) {
    List<Integer> ret = new ArrayList<Integer>();

    for(int i = 0; i < nums.length; i++) {
        int val = Math.abs(nums[i]) - 1;
        if(nums[val] > 0) {
            nums[val] = -nums[val];
        }
    }

    for(int i = 0; i < nums.length; i++) {
        if(nums[i] > 0) {
            ret.add(i+1);
        }
    }
    return ret;
}
發佈了84 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章