找到所有数组中隐没的数字
题目形容:给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范畴内但没有呈现在 nums 中的数字,并以数组的模式返回后果。
示例阐明请见LeetCode官网。
起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
解法一:哈希法
首先,将1~n的数字初始化到hashSet里,而后判断原数组nums的元素如果在hashSset外面,则移除,最初剩下的就是在 [1, n] 范畴内但没有呈现在 nums 中的数字。
解法二:原地算法
首先,遍历原数组,将相应地位的元素对应的索引地位的值标记为正数,最初,再遍历一次数组,把非正数挑出来即为在 [1, n] 范畴内但没有呈现在 nums 中的数字
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.stream.Collectors;public class LeetCode_448 { /** * 哈希法 * * @param nums 原数组 * @return */ public static List<Integer> findDisappearedNumbers(int[] nums) { Set<Integer> numbers = new HashSet<>(); // 将1~n的数字初始化到hashSet里 for (int i = 1; i <= nums.length; i++) { numbers.add(i); } // 判断原数组nums的元素如果在hashSset外面,则移除,最初剩下的就是在 [1, n] 范畴内但没有呈现在 nums 中的数字 for (int num : nums) { if (numbers.contains(num)) { numbers.remove(num); } } return new ArrayList<>(numbers); } /** * 原地算法 * * @param nums 原数组 * @return */ public static List<Integer> findDisappearedNumbers2(int[] nums) { // 遍历原数组,将相应地位的元素对应的索引地位的值标记为正数 for (int i = 0; i < nums.length; i++) { int index = Math.abs(nums[i]); nums[index - 1] = Math.abs(nums[index - 1]) * -1; } // 最初,再遍历一次数组,把非正数挑出来即为在 [1, n] 范畴内但没有呈现在 nums 中的数字 List<Integer> result = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { result.add(i + 1); } } return result; } public static void main(String[] args) { int[] nums = {4, 3, 2, 7, 8, 2, 3, 1}; // 测试用例,冀望输入: 5,6 System.out.println(findDisappearedNumbers(nums).stream().map(e -> String.valueOf(e)).collect(Collectors.joining(","))); System.out.println(findDisappearedNumbers2(nums).stream().map(e -> String.valueOf(e)).collect(Collectors.joining(","))); }}
【每日寄语】 为人贵在“实”,工作贵在“专”,学习贵在“恒”。