Leetcode 448. Find All Numbers Disappeared in an Array

来源:互联网 发布:linux ndk 编译的so 编辑:程序博客网 时间:2024/05/18 00:49

o(n) time and space

public class Solution {    public List<Integer> findDisappearedNumbers(int[] nums) {        List<Integer> list = new ArrayList<Integer>();        int[] res = new int[nums.length];        for (int num : nums)             res[num-1] = num;        for (int i=0; i<res.length; i++)             if (res[i] == 0) list.add(i+1);        return list;    }}

o(n) time o(1) space

/** * first interation, * apply nums[nums[i]-1] = -nums[nums[i]-1] to mark all numbers appear in the array as negative  * second interation, * find out which numbers are missing */ public class Solution {    public List<Integer> findDisappearedNumbers(int[] nums) {        List<Integer> list = new ArrayList<Integer>();        for (int num : nums) {            num = Math.abs(num);            if (nums[num-1] > 0) nums[num-1] = -nums[num-1];        }                    for (int i=0; i<nums.length; i++)            if (nums[i] > 0) list.add(i+1);        return list;    }}


0 0
原创粉丝点击