本文主要是介绍leetcode448~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
Input:
[4,3,2,7,8,2,3,1]Output:
[5,6]
public List<Integer> findDisappearedNumbers3(int[] nums) {List<Integer> res = new ArrayList<Integer>();for(int i=0;i<nums.length;i++) {//如果是重复的数,则只会标记一个,变为相反数//将数放到对应的索引位置上 如位置i上放i+1int val = Math.abs(nums[i])-1;if(nums[val]>0) {//标记为负数nums[val] = -nums[val];}}//经过上一步的标记,正常出现的数都变负了for(int i=0;i<nums.length;i++) {if(nums[i]>0) {res.add(i+1);}}return res;}public List<Integer> findDisappearedNumbers(int[] nums) {List<Integer> res = new ArrayList<Integer>();int len = nums.length;for(int i=0;i<len;i++) {nums[(nums[i]-1)%len] += len;}for(int i=0;i<len;i++) {if(nums[i]<=len) {res.add(i+1);}}return res;}
这篇关于leetcode448~Find All Numbers Disappeared in an Array的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!