Created
November 8, 2018 23:20
-
-
Save qiaoxu123/bf07512f87167f8bd6a7fd902025704e to your computer and use it in GitHub Desktop.
给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。 找到所有出现两次的元素。 你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗? 示例: 输入:
[4,3,2,7,8,2,3,1] 输出:
[2,3]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//思路:第一次尝试,使用了额外空间来对数组元素进行计数 | |
//时间:104 ms | |
class Solution { | |
public: | |
vector<int> findDuplicates(vector<int>& nums) { | |
vector<int> array = nums; | |
vector<int> find_array; | |
array.push_back(0); | |
for(int i = 0;i < array.size();++i) | |
array[i] = 0; | |
for(int i = 0;i < nums.size();++i) | |
array[nums[i]] += 1; | |
for(int i = 0;i < array.size();++i){ | |
if(array[i] == 2) | |
find_array.push_back(i); | |
} | |
return find_array; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment