1 package BitManipulation; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 //Question 448. Find All Numbers Disappeared in an Array 7 /* 8 Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), 9 some elements appear twice and others appear once. 10 11 Find all the elements of [1, n] inclusive that do not appear in this array. 12 Could you do it without extra space and in O(n) runtime? 13 You may assume the returned list does not count as extra space. 14 Example: 15 16 Input: 17 [4,3,2,7,8,2,3,1] 18 19 Output: 20 [5,6] 21 */ 22 public class findDisappearedNumbers448 { 23 public static List<Integer> findDisappearedNumbers(int[] nums) { 24 List<Integer> result=new ArrayList<Integer>(); 25 int len=nums.length; 26 for(int i=0;i<len;i++){ 27 nums[(nums[i]-1)%len]+=len; 28 } 29 for(int i=0;i<len;i++){ 30 if(nums[i]<=len){ 31 result.add(i+1); 32 } 33 } 34 return result; 35 } 36 public static void main(String[] args){ 37 //int[] nums={2,2,1}; 38 int[] nums={4,3,2,7,8,2,3,1}; 39 //System.out.println(findDisappearedNumbers(nums)); 40 System.out.println(findDisappearedNumbers2(nums)); 41 } 42 43 //study the solution of other people 44 //example1:原理是一样的,只是一个用的是绝对值,一个用的是取余 45 public static List<Integer> findDisappearedNumbers2(int[] nums) { 46 List<Integer> result=new ArrayList<Integer>(); 47 int len=nums.length; 48 for(int i=0;i<len;i++){ 49 nums[Math.abs(nums[i])-1]=-Math.abs(nums[Math.abs(nums[i])-1]); 50 } 51 for(int i=0;i<len;i++){ 52 if(nums[i]>0){ 53 result.add(i+1); 54 } 55 } 56 return result; 57 } 58 59 60 61 }
LeetCode:448. Find All Numbers Disappeared in an Array
原文:http://www.cnblogs.com/luluqiao/p/6255854.html