448. Find All Numbers Disappeared in an Array | 找出数组没有的数

来源:互联网 发布:作弊神器软件下载 编辑:程序博客网 时间:2024/06/04 21:12

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[nums[i]-1]换成nums[nums[i]-1]=nums[nums[i]-1]-nums.length,如果对应的nums[i]已经小于或等于0,那t = nums[i]-1+nums.length,再讲nums[nums[i]-1]重新赋值,但是如果nums[nums[i]-1]已经是小于等于0的数则不再重新赋值。

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



看到答案,其实有比我更简洁的方法,就是将对应的nums[(nums[i]-1)%n]+=n.代码确实简便很多。

0 0
原创粉丝点击