数组中寻找重复数字或缺失数字的记负法思想
2018-03-04 15:49
441 查看
记负法
出现在给一个数组的情况,数组中的数只出现一次或者两次,求出现两次的数字,或者未出现的数。对于数组下标[0,n-1],数值的范围是
[1,n]。
我们可以扫描一遍,将数字
i的对应位置·
i-1的值
nums[i-1]置为负,即令
nums[i-1] = -nums[i-1], 这样,就不用额外的空间来记录某个数字是否出现。
用这样的方法,可以时间复杂度做到
O(n), 空间复杂度做到
O(1),极其优秀。
例题
1.442. Find All Duplicates in an Array
https://leetcode.com/problems/find-all-duplicates-in-an-array/description/参考代码
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { int len = nums.size(), val; vector<int> ans; for(int i = 0; i < len; i++) { val = abs(nums[i])-1; nums[val] = - nums[val]; if(nums[val] > 0) ans.push_back(val+1); } return ans; } };
2.448. Find All Numbers Disappeared in an Array
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/参考代码
class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { int len = nums.size(), val; for(int i = 0; i < len; i++) { val = abs(nums[i])-1; if(nums[val] > 0) { nums[val] = -nums[val]; } } vector<int> ans; for(int i = 0; i < len; i++) { if(nums[i] > 0) { ans.push_back(i+1); } } return ans; } };
相关文章推荐
- 寻找连续数组中缺失的数字!!
- 数组中的重复(缺失)数字 剑指offer3 及扩展
- 合法IP&窗口最大值数组&打印素数&递归逆序一个栈&栈排序另一个栈&MyString&寻找数组中出现的重复字符&数组中的重复数字&逆序打印链表&空格替换成%20
- 寻找重复数字(数组作下标)
- 位图法寻找数组中重复出现的数字
- 利用快排思想寻找数组中第K大(小)的数字
- 寻找数组中和为指定数字的子数组,可以重复,Leetcode 39
- 寻找数组中的第K大的元素&找数组中重复数字
- 剑指offer--数组中重复的数字
- 计蒜客第22题---排序后的数组删除重复数字
- 每天一道LeetCode-----有序数组循环右移n位后,寻找最小值,数组中可能包含重复元素
- randnumber_mn.c 生成一个数组,包括k个不重复的整数,并且要求这些整数范围为[m,n),生成的结果中不能包含inum中的数字,size表示inum的长度
- 删除排序数组中的重复数字
- 数组中重复的数字
- 剑指Offer-面试题3 数组中重复的数字
- 剑指offer35题:第一个只出现一次的字符+剑指offer55题:字符流中第一个不重复的字符+剑指offer51题:数组中重复的数字
- 计蒜客 22题 排序后的数组删除重复数字
- 计蒜客题目 排序后的数组删除重复数字
- 整数数组从1到32000,4KB内存,输出重复的数字
- 剑指offer51题(数组中重复的数字)