LeetCode-Find All Duplicates in an Array & Find All Numbers Disappeared in an Array

来源:互联网 发布:知乎电影1942精彩片段 编辑:程序博客网 时间:2024/06/04 21:27

1. Find All Duplicates in an Array(Medium)

Description
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:

Input:[4,3,2,7,8,2,3,1]Output:[2,3]

Analysis
分析题意,题目要求找到所有重复出现的数字,我们可以用正负号来标记每个数字出现的次数,遍历nums,记当前数字为n(取绝对值),将数字n视为下标(因为a[i]∈[1, n])

  • 当n首次出现时,nums[n - 1]乘以-1
  • 当n再次出现时,则nums[n - 1]一定<0,将n加入答案

代码:

class Solution {public:    vector<int> findDuplicates(vector<int>& nums) {        vector<int> result;        for (int num : nums) {            if (nums[abs(num) - 1] < 0) {                result.push_back(abs(num));            } else {                nums[abs(num) - 1] *= -1;            }        }        return result;    }};

2. Find All Numbers Disappeared in an Array(Easy)

Description
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]

Analysis
这题和上一题类似,也可以用正负号来标记数字是否消失。首先遍历nums,数字num首次出现,则将nums[abs(num) - 1]变为负数,num第二次出现,nums[abs(num) - 1]小于0,则不做任何操作。最后用一个循环把所有数字为正的下标加上1放入结果vector中。

代码:

class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        vector<int> result;        for (int num : nums) {            if (nums[abs(num) - 1] > 0) {                nums[abs(num) - 1] *= -1;            }        }        for (int i = 0; i < nums.size(); i++) {            if (nums[i] > 0)                result.push_back(i + 1);        }        return result;    }};
阅读全文
0 0
原创粉丝点击