https://leetcode.com/problems/single-number/
这是来自于leetcode上的一道题目。这里主要强调的是解决题目时候必须数学先行。题目虽然很简单,不假思考就可以给出几个很直观的答案,但是由于时间复杂度是O(nlogn)空间复杂度是O(n)
Given an 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?
class Solution { public: int singleNumber(vector<int>& nums) { sort(nums.begin(),nums.end()); for(int i=0;i<nums.size();i++) { if(i+1<nums.size()) if(nums[i]==nums[i+1]) i++; else return nums[i]; if(i+1==nums.size()) return nums[i]; } } };
class Solution { public: int singleNumber(vector<int>& nums) { unordered_map<int ,int>umap; for(int i=0;i<nums.size();i++) umap[nums[i]]++; for(auto it:umap) if(it.second==1) return it.first; } };
class Solution { public: int singleNumber(vector<int>& nums) { int res=0; for(int i=0;i<nums.size();i++) res^=nums[i]; return res; } };
如果能直接给出
result=f(已知条件)
这样的函数,那么问题就会简单很多!
原文:http://blog.csdn.net/zhouyelihua/article/details/46508551