标签:它的 script lin public ret output 其它 哈希 with
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
class Solution { public: int singleNumber(vector<int>& nums) { unordered_set<int> numlist; for(int i=0;i<nums.size();i++) { if(numlist.count(nums[i])!=0) numlist.erase(nums[i]); else(numlist.insert(nums[i])); } auto it = numlist.begin(); return *it; } };
思路二:对数组排序,两个一组依次进行比较,直到有不相等的两个数,两个数中的第一个就是那个只出现了一次的数
class Solution { public: int singleNumber(vector<int>& nums) { int len=nums.size(); sort(nums.begin(),nums.end()); int i=0;; while(i<len-1) { if(nums[i]==nums[i+1]){ i+=2; } else break; } return nums[i]; } };
标签:它的 script lin public ret output 其它 哈希 with
原文地址:https://www.cnblogs.com/Bipolard/p/9994216.html