leetcode Find All Numbers Disappeared in an Array 找数组中消失的元素
来源:互联网 发布:java中todo 编辑:程序博客网 时间:2024/06/09 17:45
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]
题意:一个长为n的数组,存储1到n的数,其中右重复的,找出数组中不存在的1~n之间的数,要求时间复杂度为O(n),空间复杂度为O(1);
思路:遍历数组,将数组中元素a[i]对应下标所对应的元素a[a[i]]取负,代表元素a[i]存在,遍历数组,数组中正数元素对应的下标即为消失的元素。
即为节省空间,用原数组元素的正负来标记对应下标数是否存在。
class Solution {public: vector<int> findDisappearedNumbers(vector<int>& nums) { int len = nums.size(); vector<int> ans; for (int i = 0; i < len; ++i) { int temp = abs(nums[i]) - 1; nums[temp] = nums[temp] > 0 ? -nums[temp] : nums[temp]; } for (int i = 0; i < len; ++i) { if (nums[i] > 0) ans.push_back(i + 1); } return ans; }};
阅读全文
0 0
- leetcode Find All Numbers Disappeared in an Array 找数组中消失的元素
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- [LeetCode]448. Find All Numbers Disappeared in an Array(查找数组中消失的所有数字)
- 448. Find All Numbers Disappeared in an Array 找出数组中消失的数
- 448.Find All Numbers Disappeared in an Array 找出数组中所有消失的数字
- LeetCode--Find All Numbers Disappeared in an Array(找到数组中未出现的数字)
- leetcode -- 448. Find All Numbers Disappeared in an Array【数组】
- Leetcode 448. Find All Numbers Disappeared in an Array 找没有的数 解题报告
- LeetCode 448. Find All Numbers Disappeared in an Array(查找数组中没有出现的数字)
- leetcode 448Find All Numbers Disappeared in an Array (array)
- LeetCode-Array-448. Find All Numbers Disappeared in an Array
- LeetCode OJ|Array|Find All Numbers Disappeared in an Array
- LeetCode OJ|Array| Find All Numbers Disappeared in an Array
- LeetCode刷题【Array】 Find All Numbers Disappeared in an Array
- [LeetCode]Find All Numbers Disappeared in an Array
- leetcode:448. Find All Numbers Disappeared in an Array
- LeetCode 448. Find All Numbers Disappeared in an Array
- LeetCode No.448 Find All Numbers Disappeared in an Array
- MATLAB worldmap 仿真图处理
- java---懒汉式的线程安全问题
- 使用指针在函数间通信
- 加密解密
- C语言基础
- leetcode Find All Numbers Disappeared in an Array 找数组中消失的元素
- Struts2 FilterDispatcher核心控制器
- BZOJ 3036 绿豆蛙的归宿 期望动规
- 第6章 接口(与抽象类的比较)
- Spring Boot常见问题(二)Unable to start embedded container; nested exception is java.lang.NoSuchMethodErro
- linux进阶之旅(二)& LVS
- java---Thread(Account)
- UVA 10474 【排序与查找】
- Centos6.5安装epel