LeetCode Find All Numbers Disappeared in an Array

来源:互联网 发布:八大网络虚拟人物图片 编辑:程序博客网 时间:2024/05/18 03:22

题意:给出长度为n的数组,数组的数为 1-n,找出没有出现的数

思路:在遍历数组时,将对应的索引的数设置为负数。第二次遍历数组时,索引所在的数为正数,说明是没有出现的

代码如下:

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


0 0
原创粉丝点击