package leetcode.array; import java.util.ArrayList; import java.util.List; /** * Created by w84108989 on 2019/2/21. */ //给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。 // // 找到所有在 [1, n] 范围之间没有出现在数组中的数字。 // // 您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。 // // 示例: // // 输入: // [4,3,2,7,8,2,3,1] // // 输出: // [5,6] public class disappear_448 { public static void main(String[] args) { int[] n = {4,3,2,7,8,2,3,1}; System.out.println(findDisappearedNumbers(n)); } public static List<Integer> findDisappearedNumbers(int[] nums) { // List<Integer> l = new ArrayList<>(); // List<Integer> res = new ArrayList<>(); // for (int i = 0; i < nums.length; i++) { // l.add(nums[i]); // } // for (int i = 1; i <= nums.length; i++) { // if (!l.contains(i)){ // res.add(i); // } // } // return res; List<Integer> result = new ArrayList<>(); for (int num : nums) { int index = Math.abs(num) - 1; if (nums[index] > 0) nums[index] = -nums[index]; } //找到正数的索引 int size = nums.length; for (int i = 0; i < size; i++) if (nums[i] > 0) result.add(i + 1); return result; } }
leetcode_448
最新推荐文章于 2021-02-13 11:02:57 发布