C++算法题_第一周

来源:互联网 发布:2016淘宝客刷销量 编辑:程序博客网 时间:2024/05/28 23:23

题目来源    点击打开链接

题目详情     

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]
题目解答

class Solution {public:    vector<int> findDuplicates(vector<int>& nums) {        int leng = nums.size();        map<int, bool> twice;        vector<int> ret;        for(int i = 0; i < leng; i++){        map<int, bool>::iterator it;        it = twice.find(nums[i]);        if(it != twice.end()) twice[nums[i]] = 1;        else{        twice[nums[i]] = 0;}}map<int, bool>::iterator itr;itr = twice.begin();for(; itr!=twice.end(); itr++){if((*itr).second) ret.push_back((*itr).first);}return ret;    }};

0 0
原创粉丝点击