package com.leetcode;
import java.util.*;
/**
* LeetCode448FindDisappearedNumInArr:找出所有数组中消失的数字
*/
public class LeetCode448FindDisappearedNumInArr {
/**
* 方法1.hashset,找出没出现的数字
*/
public static List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int n = nums.length;
for (int i = 1; i <= n; i++) {
if (!set.contains(i)) {
result.add(i);
}
}
return result;
}
/**
*
* @param nums
* @return
*/
public static List<Integer> findDisappearedNumbers2(int[] nums) {
int n=nums.length;
//1.对数组中数字进行遍历
for (int num : nums) {
//对n取模来还原出本来的值
int x=(num-1)%n;
nums[x]+=n;
}
List<Integer> result=new ArrayList<>();
for(int i=0;i<n;i++){
//2.找出数组中缺失的数值
if(nums[i]<=n){
result.add(i+1);
}
}
return result;
}
public static void main(String[] args) {
// int[] nums = {4, 3, 2, 7, 8, 2, 3, 1};
// System.out.println("findDisappearedNumbers(nums) = " + findDisappearedNumbers(nums));
// int[] nums = {1,1};
// System.out.println("findDisappearedNumbers(nums) = " + findDisappearedNumbers(nums));
// int[] nums = {4, 3, 2, 7, 8, 2, 3, 1};
// System.out.println("findDisappearedNumbers2(nums) = " + findDisappearedNumbers2(nums));
int[] nums = {1,1};
System.out.println("findDisappearedNumbers2(nums) = " + findDisappearedNumbers2(nums));
}
}
标签:java,nums,int,List,LeetCode448,算法,num,result,new
From: https://blog.csdn.net/crazy123456789/article/details/143688890