LeetCode448~Find All Numbers Disappeared in an Array

Find All Numbers Disappeared in an Array

Description

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 1
Input: [4,3,2,7,8,2,3,1]

Output: [5,6]

Solution1:暴力

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

Solution2:Set

package Easy;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author:DaciVin
 * @version:2019年12月1日
 */
public class sol2 {

	/**
	 * @param args
	 * @return 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
List<Integer>list=new ArrayList<Integer>();
Set<Integer>set=new HashSet();

for(int i=1;i<=8;i++) {
	set.add(i);
}
int []nums={3,4,3,4,1,2,7,8}; 
for (int k : nums) {
    set.remove(k);
}
List<Integer>lis=new ArrayList(set);
for (int i=0; i<lis.size(); i++) {
    int s = lis.get(i);
    System.out.println(s);
}
	}

}

Appendix

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章