Leetcode——Array 2

来源:互联网 发布:淘宝买鹿王羊绒衫 编辑:程序博客网 时间:2024/06/06 22:08

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]

思路:
个人做该题的第一思路是排序,然后遍历查找nums[i] - nums[i - 1] > 1的间隔,但是算法复杂度是O(nlog2n)的。而别人的解答主要是直接在原来的数组上进行修改,一种是将nums[Math.abs(nums[i])- 1]取反,另一种是将nums[nums[i] - 1] += n;之后在进行一次遍历,确定缺少的数字。

代码实现:

public class Solution {    public List<Integer> findDisappearedNumbers(int[] nums) {        ArrayList<Integer> list = new ArrayList<Integer> ();        for(int i = 0; i < nums.length; i++){            int value = Math.abs(nums[i])-1;            if(nums[value] > 0) nums[value] = -nums[value]; // remember to add if, otherwise -(-a) may occur        }        for(int i = 0; i < nums.length; i++){            if(nums[i] >= 0) list.add(i+1);        }        return list;    }}

类似的还有:442. Find All Duplicates in an Array

0 0
原创粉丝点击