448. Find All Numbers Disappeared in an Array

来源:互联网 发布:博微配网设计软件 编辑:程序博客网 时间:2024/04/28 21:52

448. Find All Numbers Disappeared in an Array

 
 My Submissions
  • Total Accepted: 12715
  • Total Submissions: 22023
  • Difficulty: Easy
  • Contributors: yuhaowang001

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.

public class Solution {    public List<Integer> findDisappearedNumbers(int[] nums) {        List<Integer> result=new ArrayList<Integer>();    for(int i=0;i<nums.length;i++)    {    if(nums[i]==i+1)    continue;    else    {    int index=nums[i]-1;    while(nums[index] != (index+1))    {    int index_=nums[index]-1;    nums[index]=index+1;    index=index_;        }    }    }    for(int i=0;i<nums.length;i++)    {    if(nums[i]!=(i+1))    result.add(i+1);    }    return result;    }}

Input:[4,3,2,7,8,2,3,1]Output:

[5,6]

Tips:因为数组中元素是1-N之间的(N为数组长度),那我们只要循环将数据元素放回其应该待的位置就可以的(比如2,1,3,4,其中第一个位置遇到2,2应该在索引为2-1=1的地方,所以我们把数据索引为1的数据改为2,同样的该位置原来的1应该在索引1-1=0的地方,将索引为0的数据改为1)

0 0
原创粉丝点击