448.|448. Find All Numbers Disappeared in an Array
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: 【448.|448. Find All Numbers Disappeared in an Array】思路:
The basic idea is that we iterate through the input array and mark elements as negative using nums[nums[i] -1] = -nums[nums[i]-1]. In this way all the numbers that we have seen will be marked as negative. In the second iteration, if a value is not marked as negative, it implies we have never seen that index before, so just add it to the return list.
Time Complexity: O(N) Space Complexity: O(1)
Solution Code:
class Solution {
public List findDisappearedNumbers(int[] nums) {
List ret = new ArrayList();
for(int i = 0;
i < nums.length;
i++) {
int val = Math.abs(nums[i]) - 1;
if(nums[val] > 0) {
nums[val] = -nums[val];
}
}for(int i = 0;
i < nums.length;
i++) {
if(nums[i] > 0) {
ret.add(i+1);
}
}
return ret;
}
}
推荐阅读
- parallels|parallels desktop 解决网络初始化失败问题
- Android|Android install 多个设备时指定设备
- oracle|oracle java jdk install
- JavaScript|JavaScript — call()和apply()、Date对象、Math、包装类、字符串的方法
- c语言|一文搞懂栈(stack)、堆(heap)、单片机裸机内存管理malloc
- 运行报错Cannot|运行报错Cannot find module '@babel/compat-data/corejs3-shipped-proposals’
- 2018-11-13每日一词|2018-11-13每日一词 42 | parallel - 草稿
- 文件解压缩及搜索文件find
- 201708期+283号+薛泽明Allen+Day34
- pyinstaller解决闪退问题