Problem
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:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]Solution
class Solution { public ListfindDisappearedNumbers(int[] nums) { List res = new ArrayList<>(); if (nums == null || nums.length == 0) return res; for (int i = 0; i < nums.length; i++) { int index = nums[i] > 0 ? nums[i]-1 : -nums[i]-1; if (nums[index] < 0) continue; nums[index] *= -1; } for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) res.add(i+1); } return res; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/73015.html
Problem 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...
摘要:如果这个位置的值为正意味着我们还没有对这个元素进行过操作,我们将这个位置的元素的值取负。在整个遍历结束后,没有取负的值的索引,就可以对应到没有在数组出现过的值解法 题目详情 Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others ap...
摘要:题目要求假设一个长度为的整数数组,数组中的元素的值位于区间中。代码如下但是这个实现违背了的空间复杂度这里结果集不视为额外空间。如果当前元素无需进行交换,则指针右移一位。无需进行的场景是指当前元素已经出现在目标位置上了。 题目要求 Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some element...
摘要:题目链接一般这种类型的题要,要么给赋值成不在范围内的数,要么到对应位置。 448. Find All Numbers Disappeared in an Array 题目链接:https://leetcode.com/problems... 一般这种类型的题要in place,要么给num[i]赋值成不在范围内的数,要么swap到对应位置。 public class Solution ...
摘要:题目链接题目分析给定一个到的数组,返回其中缺失的数字。思路用得出到的数字,再用和给定的数组计算差集。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D79 448. Find All Numbers Disappeared in an Array 题目链接 448. Find All Numbers Disappeared in an Array 题目分析 给定一个1到n的数组,返回...
阅读 2243·2021-11-23 10:09
阅读 2778·2021-10-12 10:11
阅读 2563·2021-09-29 09:35
阅读 1310·2019-08-30 15:53
阅读 2227·2019-08-30 11:15
阅读 2876·2019-08-29 13:01
阅读 2259·2019-08-28 18:15
阅读 3329·2019-08-26 12:13