Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts

Saturday, May 30, 2015

217 Contains Duplicate

来源:Leetcode

原帖:https://leetcode.com/problems/contains-duplicate/

题目:
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

代码:
 class Solution {  
 public:  
   bool containsDuplicate(vector<int>& nums) {  
     unordered_set<int> _set;  
     for (auto i : nums) {  
       if (_set.count(i)) return true;  
       _set.insert(i);  
     }  
     return false;  
   }  
 };  

Monday, May 18, 2015

Subsets II

来源:Leetcode

原帖:http://oj.leetcode.com/problems/subsets-ii/

题目:
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
 [
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
 ]

代码:
 class Solution {  
 public:  
   //Version 1: 从树状结构考虑递归方法  
   vector<vector<int> > subsetsWithDup(vector<int> &S) {  
     vector<vector<int> > result;  
     if (S.empty()) return result;  
     sort(S.begin(), S.end());  
     vector<int> oneset;  
     subsetsWithDupHelper(S, 0, oneset, result);  
     return result;  
   }  
   
   void subsetsWithDupHelper(vector<int> &S, int start, vector<int> &oneset, vector<vector<int> > &result) {  
     result.push_back(oneset);  
     for (int i = start; i < S.size(); ++i) {  
       if (i != start && S[i] == S[i - 1]) {  
         continue;  
       }    
       oneset.push_back(S[i]);  
       subsetsWithDupHelper(S, i + 1, oneset, result);  
       oneset.pop_back();  
     }  
   }   
 };  
   
 // {}  
 // 1  
 // 2  
 // 1,2  
 // 2,2  
 // 1,2,2  
 class Solution {  
 public:  
   vector<vector<int> > subsetsWithDup(vector<int> &S) {  
     sort(S.begin(), S.end());  
     vector<vector<int>> ret = {{}};  
     int size = 0, startIndex = 0;  
     for (int i = 0; i < S.size(); i++) {  
       startIndex = i >= 1 && S[i] == S[i - 1] ? size : 0;  
       size = ret.size();  
       for (int j = startIndex; j < size; j++) {  
         vector<int> temp = ret[j];  
         temp.push_back(S[i]);  
         ret.push_back(temp);  
       }  
     }  
     return ret;  
   }  
 };  

Subsets I

来源:Leetcode

原帖:http://oj.leetcode.com/problems/subsets/

题目:
Given a set of distinct integers, S, return all possible subsets.
Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3], a solution is:
 [
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
 ]

代码:
 class Solution {  
 public:  
   void subsetHelper(const vector<int> &S, int start, vector<int> &oneset, vector<vector<int> > &result) {  
     result.push_back(oneset);  
     for (int i = start; i < S.size(); ++i) {  
       oneset.push_back(S[i]);  
       subsetHelper(S, i + 1, oneset, result);  
       oneset.pop_back();  
     }  
   }  
   
   //Version 1: 从树状结构考虑递归方法  
   vector<vector<int> > subsets(vector<int> &S) {  
     vector<vector<int> > result;  
     if (S.empty()) return result;  
     sort(S.begin(), S.end());  
     vector<int> oneset;  
     subsetHelper(S, 0, oneset, result);  
     return result;  
   }  
 };  
   
 // Bitwise solution. each bit has two state, present or not.  
 class Solution {  
 public:  
   vector<vector<int> > subsets(vector<int> &S) {  
     sort (S.begin(), S.end());  
     int elem_num = S.size();  
     int subset_num = pow (2, elem_num);  
     vector<vector<int> > subset_set (subset_num, vector<int>());  
     for (int i = 0; i < elem_num; i++)  
       for (int j = 0; j < subset_num; j++)  
         if ((j >> i) & 1)  
           subset_set[j].push_back (S[i]);  
     return subset_set;  
   }  
 };  
   
 // iteration  
 class Solution {  
 public:  
   vector<vector<int> > subsets(vector<int> &S) {  
     vector<vector<int> > R;  
     R.push_back(vector<int>());  
     sort(S.begin(), S.end());  
     for (int i = 0; i<S.size(); i++) {  
       int Rsize = R.size();  
       for (int j = 0; j<Rsize; j++) {  
         vector<int> sub(R[j]);  
         sub.push_back(S[i]);  
         R.push_back(sub);  
       }  
     }  
     return R;  
   }  
 };  


Permutations II

来源:Leetcode

原帖:http://oj.leetcode.com/problems/permutations-ii/

题目:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
 For example,
 [1,1,2] have the following unique permutations:
 [1,1,2], [1,2,1], and [2,1,1].

代码:
 class Solution {  
 public:  
   vector<vector<int>> permuteUnique(vector<int> &num) {  
     vector<vector<int>> result;  
     if (num.empty()) return result;  
     sort(num.begin(), num.end());  
     vector<bool> avail(num.size(),true);  
     vector<int> onepum;  
     permuteHelper(num, onepum, avail, result);  
     return result;  
   }  
   
   void permuteHelper(const vector<int> &num, vector<int> &onepum, vector<bool> &avail, vector<vector<int> > &result) {  
     if (onepum.size() == num.size()) {  
       result.push_back(onepum);  
       return;  
     }  
     int last_index = -1;  
     for (int i = 0; i < num.size(); ++i) {  
       if (!avail[i]) continue;  
       // 1233 -> 1323  
       if (last_index != -1 && num[i] == num[last_index]) {  
         continue; // last_index stores the position been visited          
       }  
       avail[i] = false;  
       onepum.push_back(num[i]);  
       permuteHelper(num, onepum, avail, result);  
       onepum.pop_back();  
       avail[i] = true;  
       last_index = i;  
     }  
   }  
 };  
   

Permutations I

来源:Leetcode

原帖:http://oj.leetcode.com/problems/permutations/

题目:
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

代码:
 class Solution {  
 public:  
   vector<vector<int>> permute(vector<int> &num) {  
     if (num.empty()) {}  
     vector<vector<int> > result;  
     vector<bool> avail(num.size(), true);  
     vector<int> onepum;  
     permuteHelper(num, avail, onepum, result);  
     return result;  
   }  
   
   void permuteHelper(const vector<int> &num, vector<bool> &avail, vector<int> &onepum, vector<vector<int>> &result) {  
     if (onepum.size() == num.size()) {  
       result.push_back(onepum);  
       return;  
     }      
     for (int i = 0; i < num.size(); ++i) {  
       if (avail[i]) {  
         avail[i] = false;  
         onepum.push_back(num[i]);  
         permuteHelper(num, avail, onepum, result);  
         onepum.pop_back();  
         avail[i] = true;  
       }  
     }  
   }  
 };  


Next Permutation

来源:Leetcode

原帖:http://oj.leetcode.com/problems/next-permutation/

题目:
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place, do not allocate extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
 1,2,3 -> 1,3,2
 3,2,1 -> 1,2,3
 1,1,5 -> 1,5,1
Solution: O(n)
Processes: Take A = {1,3,2} as an example:
1. Traverse from back to forth, find the turning point, that is A[i] = 3.
2. Sort from the turning point to the end (A[i] to A[end]), so {3,2} becomes {2,3}.
            3. If i equals to 0, finish! Else, goto 4.
            4. Let j = i, search from A[j] to A[end] to find the first elem which is larger than A[i-1], '2' here.
            5. Swap the elem A[j] with A[i-1].
            Finally, the next permutation is {2,1,3}.

代码:
 class Solution {  
 public:  
   void nextPermutation(vector<int> &num) {  
     int i = num.size() - 1;  
     while (i > 0 && num[i] <= num[i - 1]) i--;        
     sort(num.begin() + i, num.end());  
     if (i == 0) return;        
     int j = i;  
     while (j < num.size() && num[j] <= num[i - 1]) j++;        
     swap(num[j], num[i - 1]);  
   }  
 };  


Minimum Path Sum

来源:Leetcode

原帖:http://oj.leetcode.com/problems/minimum-path-sum/

题目:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Solution: Dynamic Programming. Space O(N).

代码:
 class Solution {  
 public:  
   int minPathSum(vector<vector<int> > &grid) {  
     if (grid.empty()) return INT_MIN;  
     int M = grid.size(), N = grid[0].size(); // col  
     vector<int> dp(N, 0);  
     dp[0] = grid[0][0];  
     for (int i = 1; i < N; ++i) {  
       dp[i] = grid[0][i] + dp[i - 1];        
     }      
     for (int i = 1; i < M; ++i) { // row  
       dp[0] += grid[i][0];  
       for (int j = 1; j < N; ++j) { // col  
         dp[j] = min(dp[j - 1], dp[j]) + grid[i][j];  
       }  
     }  
     return dp[N - 1];  
   }  
 };  



Unique Paths II

来源:Leetcode

原帖:http://oj.leetcode.com/problems/unique-paths-ii/

题目:
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
 [
  [0,0,0],
  [0,1,0],
  [0,0,0]
 ]
The total number of unique paths is 2.
Note: m and n will be at most 100.

代码:
 class Solution {  
 public:  
   int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {  
     int m = obstacleGrid.size(), n = obstacleGrid[0].size();  
     int dp[m][n];  
     if (obstacleGrid[0][0] == 1) return 0;  
     dp[0][0] = 1;  
     for (int i = 1; i < m; i++)  
       dp[i][0] = obstacleGrid[i][0] == 1 ? 0 : dp[i - 1][0];        
     for (int j = 1; j < n; j++)  
       dp[0][j] = obstacleGrid[0][j] == 1 ? 0 : dp[0][j - 1];        
     for (int i = 1; i < m; i++) {  
       for (int j = 1; j < n; j++) {  
         dp[i][j] = obstacleGrid[i][j] == 1 ? 0: dp[i - 1][j] + dp[i][j - 1];                
       }  
     }   
     return dp[m - 1][n - 1];  
   }  
 };  
   
 // space complexity O(n).   
 class Solution {  
 public:  
   int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {  
     if (obstacleGrid.size() == 0 || obstacleGrid[0].size() == 0) return 0;  
     int m = obstacleGrid.size(), n=obstacleGrid[0].size();  
     vector<int> dp(n + 1, 0);  
     dp[1] = obstacleGrid[0][0] == 1 ? 0 : 1;  
     for (int i = 0; i < m; i++) {  
       for (int j = 1; j <= n; j++){  
         dp[j] = obstacleGrid[i][j-1] == 1 ? 0 : dp[j] + dp[j-1];  
       }  
     }  
     return dp[n];  
   }  
 };  


Unique Paths I

来源:Leetcode

原帖:http://oj.leetcode.com/problems/unique-paths/

题目:
A robot is located at the top-left corner of a m x n grid. The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there?
Solution:
Dynamic programming. UP(i,j) = UP(i-1,j) + UP(i,j-1).

代码:
 class Solution {  
 public:  
   int uniquePaths(int m, int n) {  
     int dp[m][n];  
     for (int i = 0; i < m; i++) {  
       dp[i][0] = 1;  
     }    
     for (int j = 0; j < n; j++) {  
       dp[0][j] = 1;  
     }    
     for (int i = 1; i < m; i++) {  
       for (int j = 1; j < n; j++) {  
         dp[i][j] = dp[i - 1][j] + dp[i][j - 1];  
       }  
     }  
     return dp[m - 1][n - 1];  
   }  
 };  
   
 class Solution {  
 public:  
   // 滚动数组  
   int uniquePaths(int m, int n) {  
     int dp[2][n];  
     for (int i = 0; i < n; ++i) {  
       dp[0][i] = 1;  
     }  
     dp[1][0] = 1;  
     int row = 0;  
     for (int i = 1; i < m; ++i) {  
       row = !row;  
       for (int j = 1; j < n; ++j) {  
         dp[row][j] = dp[!row][j] + dp[row][j - 1];  
       }  
     }  
     return dp[row][n - 1];  
   }  
 };  
   
 class Solution {  
 public:  
   int uniquePaths(int m, int n) {  
     vector<int> dp(n, 1);  
     for (int i = 1; i < m; ++i) {  
       for (int j = 1; j < n; ++j) {  
         dp[j] = dp[j-1] + dp[j];  
       }  
     }  
     return dp[n-1];  
   }  
 };  
   


Sunday, May 17, 2015

Jump Game II

来源:Leetcode

原帖:https://oj.leetcode.com/problems/jump-game-ii/

题目:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]. The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
Solution: Jump to the position where we can jump farthest (index + A[index]) next time.

代码:
   
 class Solution {  
 public:  
   // greedy method  
   int jump(int A[], int n) {  
     int start = 0, steps = 0;  
     while (start < n - 1) {  
       steps++;  
       if (start + A[start] >= n - 1)  
         return steps;          
       int next = start;  
       for (int i = start + 1; i <= start + A[start]; ++i) {  
         if (i + A[i] >= next + A[next])  
           next = i;  
       }  
       if (next == start) // cannot jump over the end  
         return INT_MAX;   
       start = next;  
     }  
   }  
 };  


Jump Game I

来源:Leetcode

原帖:http://oj.leetcode.com/problems/jump-game/

题目:
Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Solution: Updated solution: try every reachable index.

代码:
 class Solution {  
 public:  
   bool canJump(int A[], int n) {  
     int start = 0, farthest = 0; // farthest: 最多可以到达的状态  
     while (start <= farthest && farthest < n - 1) {  
       farthest = max(farthest, start + A[start]);  
       start++;  
     }  
     return farthest >= (n-1);  
   }  
 };  

Friday, May 15, 2015

209 Minimum Size Subarray Sum

来源:Leetcode

原帖:https://leetcode.com/problems/minimum-size-subarray-sum/

题目:
Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead. For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length under the problem constraint.

代码:
 class Solution {  
 public:  
   int minSubArrayLen(int s, vector<int>& nums) {  
     if (nums.empty()) return 0;  
     int res = INT_MAX, sum = 0;  
     int start = 0, end = 0;  
     while (end < nums.size()) {  
       sum += nums[end];  
       if (sum < s) {  
         end++; continue;  
       }  
       while (start <= end) {  
         if (sum - nums[start] >= s) {  
           sum -= nums[start++];  
         } else {  
           break;  
         }  
       }  
       res = min(res, end-start+1);  
       end++;  
     }  
     return sum < s ? 0 : res;  
   }  
 };  

Wednesday, May 13, 2015

Convert Sorted Array to Binary Search Tree

来源:Leetcode

原帖:https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

代码:
 /**  
  * Definition for binary tree  
  * struct TreeNode {  
  *   int val;  
  *   TreeNode *left;  
  *   TreeNode *right;  
  *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}  
  * };  
  */  
 class Solution {  
 public:  
   TreeNode *sortedArrayToBST(vector<int> &num) {  
     return buildBST(num, 0, num.size() - 1);  
   }  
     
   TreeNode *buildBST(vector<int> &num, int start, int end) {  
     if (start > end) return NULL;  
     int mid = start + (end - start) / 2;  
     TreeNode *root = new TreeNode(num[mid]);  
     root->left = buildBST(num, start, mid - 1);  
     root->right = buildBST(num, mid + 1, end);  
     return root;  
   }  
 };  

Interval Insert

来源:Leetcode

原帖:http://oj.leetcode.com/problems/insert-interval/

题目:
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
Solution: For example 2:
           1. compare [1,2] with [4,9], then insert [1,2];
           2. merge [3,5] with [4,9], get newInterval = [3,9];
           3. merge [6,7] with [3,9], get newInterval = [3,9];
           4. merge [8,10] with [3,9], get newInterval = [3,10];
           5. compare [12,16] with [3,10], insert newInterval [3,10], then all the remaining intervals...


代码:
 /**  
  * Definition for an interval.  
  * struct Interval {  
  *   int start;  
  *   int end;  
  *   Interval() : start(0), end(0) {}  
  *   Interval(int s, int e) : start(s), end(e) {}  
  * };  
  */  
 class Solution {  
 public:  
   vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {  
     vector<Interval> res;  
     if (intervals.empty()) {  
       res.push_back(newInterval);  
       return res;  
     }  
     bool inserted = false;  
     for (int i = 0; i < intervals.size(); ++i) {  
       if (inserted || intervals[i].end < newInterval.start) { // non-overlaping  
         res.push_back(intervals[i]);  
       } else if (newInterval.end < intervals[i].start) {  
         res.push_back(newInterval);  
         res.push_back(intervals[i]);  
         inserted = true;  
       } else { // update new interval  
         newInterval.start = min(intervals[i].start, newInterval.start);  
         newInterval.end = max(intervals[i].end, newInterval.end);  
       }  
     }  
     if (!inserted) res.push_back(newInterval);        
     return res;  
   }  
 };  

Merge Intervals

来源:Leetcode

原帖:http://oj.leetcode.com/problems/merge-intervals/

题目:
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18].
Solution: Sort in ascending order of 'start'. Traverse the 'intervals', merge or push...

代码:
 /**  
  * Definition for an interval.  
  * struct Interval {  
  *   int start;  
  *   int end;  
  *   Interval() : start(0), end(0) {}  
  *   Interval(int s, int e) : start(s), end(e) {}  
  * };  
  */  
 bool compare(const Interval& a, const Interval& b) {  
   return a.start < b.start;  
 }  
   
 class Solution {  
 public:  
   vector<Interval> merge(vector<Interval> &intervals) {  
     int N = intervals.size();  
     if (N <= 1) return intervals;  
     sort(intervals.begin(), intervals.end(), compare);  
     vector<Interval> res;  
     Interval last = intervals[0];  
     for (int i = 1; i < N; ++i) {  
       if (intervals[i].start > last.end) {  
         res.push_back(last);  
         last = intervals[i];  
       } else {  
         last.end = max(last.end, intervals[i].end);  
       }  
     }   
     res.push_back(last); // push back the last one  
     return res;  
   }  
 };  

Gray Code

来源:Leetcode

原帖:http://oj.leetcode.com/problems/gray-code/

题目:
The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0  00 ^ 00
01 - 1  00 ^ 01
11 - 3  01 ^ 10
10 - 2  01 ^ 11
Note:
For a given n, a gray code sequence is not uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
3位数情况
000
001
011
010
110
111 //如果按照题意的话,只是要求有一位不同,这里也可以是100
101
100

代码:
 //Iteration  
 class Solution {  
 public:  
   vector<int> grayCode(int n) {    
     vector<int> result;     
     result.push_back(0);   
     for (int i = 0; i < n; i++) {   
       int highestBit = 1 << i;   
       int len = result.size();   
       for (int i = len - 1; i >= 0; i--) {  // reverse  
         result.push_back(highestBit + result[i]); // highest bit  
       }    
     }   
     return result;   
   }  
 };  
   
 //Recursion  
 class Solution {  
 public:  
   vector<int> reverse(const vector<int> & r) {  
     vector<int> rev;  
     for (int i = r.size() - 1; i >= 0; --i) {  
       rev.push_back(r[i]);  
     }  
     return rev;  
   }  
     
   vector<int> grayCode(int n) {  
     vector<int> result;  
     if (n <= 1) {  
       for (int i = 0; i <= n; ++i)  
         result.push_back(i);  
       return result;  
     }  
     result = grayCode(n - 1);  
     vector<int> r1 = reverse(result);  
     for (int i = 0; i < r1.size(); ++i) {  
       int x = 1 << (n - 1);  
       r1[i] += x;  
     }  
   
     for (int i = 0; i < r1.size(); ++i) {  
       result.push_back(r1[i]);  
     }  
     return result;  
   }  
 };  
   

Gas Station

来源:Leetcode

原帖:http://oj.leetcode.com/problems/gas-station/

题目:
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next
station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. The solution is guaranteed to be unique.

代码:
 class Solution {  
 public:  
   //http://fisherlei.blogspot.com/search?q=gas  
   //0到n之间,找到第一个连续子序(这个子序列的结尾必然是n)大于0 从i起gas[i] >0,   
   //然后gas[i:i+1],until j, if Gas[i:j] < 0,then [i,j]都不能作为起点。  
   int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {  
     int N = gas.size();  
     int leftGas = 0, sum = 0, start = 0;  
     for (int i = 0; i < N; i++) {  
       int diff = gas[i] - cost[i];  
       leftGas += diff;  
       sum += diff;  
       if (sum < 0) {  
         start = i + 1;  
         sum = 0;  
       }   
     }  
     return leftGas >= 0 ? start : -1;  
   }  
 };  

Monday, May 11, 2015

Majority Element III

来源:Lintcode

原帖:http://www.lintcode.com/en/problem/majority-number-iii/

题目:
Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array. Find it. There is only one majority number in the array.
Example
For [3,1,2,3,2,1,3,1,2,3,3,4,4,4] and k = 3, return 3.

代码:
 class Solution {  
 public:  
   int majorityNumber(vector<int> nums, int k) {  
     int n = nums.size();  
     unordered_map<int, int> map; // <key, count>  
     for (int i = 0; i < n; ++i) {  
       if (map.count(nums[i])) {  
         map[nums[i]]++;  
       } else if (map.size() < k) {  
         map[nums[i]] = 1;  
       } else {  
         unordered_set<int> set;  
         for (auto it = map.begin(); it != map.end(); it++) {  
           it->second--;  
           if (it->second == 0) {  
             set.insert(it->first);  
           }  
         }  
         for (auto i : set) {  
           map.erase(i);  
         }  
       }  
     }  
     
     // find all remaining candidates  
     unordered_map<int, int> tmap;  
     for (auto it = map.begin(); it != map.end(); it++) {  
       tmap[it->first] = 0;  
     }  
     
     int count = 0, result = 0;  
     for (int i = 0; i < n; ++i) {  
       if (tmap.find(nums[i]) != tmap.end()) {  
         tmap[nums[i]]++;  
         if (tmap[nums[i]] > count) {  
           count = tmap[nums[i]];  
           result = nums[i];  
         }  
       }  
     }  
     return result;  
   }  
 };  
   

Majority Element II

来源:Lintcode

原帖:http://www.lintcode.com/en/problem/majority-number-ii/

题目:
Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array. Find it. Note: There is only one majority number in the array
Example: For [1, 2, 1, 2, 1, 3, 3] return 1. O(n) time and O(1) space

代码:
 class Solution {  
 public:  
   int computeTimes(const vector<int> &nums, int target) {  
     int count = 0;  
     for (const int &i : nums) {  
       if (i == target)   
         count++;  
     }  
     return count;  
   }  
   
   int majorityNumber(vector<int> nums) {  
     int candidate1 = 0, candidate2 = 0;  
     int count1 = 0, count2 = 0;  
     for (int i = 0; i < nums.size(); ++i) {  
       if (count1 == 0) {  
         if (count2 != 0 && candidate2 == nums[i]) {  
           count2++;  
         } else {  
           candidate1 = nums[i];  
           count1++;  
         }  
       } else {  
         if (candidate1 == nums[i]) {  
           count1++;      
         } else if (count2 == 0) {  
           count2++;   
           candidate2 = nums[i];  
         } else if (candidate2 == nums[i]) {  
           count2++;  
         } else {  
           count1--;   
           count2--;  
         }  
       }  
     }  
     if (count1 == 0) {  
       return candidate2;  
     } else if (count2 == 0) {  
       return candidate1;  
     } else {  
       return computeTimes(nums, candidate1) > computeTimes(nums, candidate2) ?   
         candidate1 : candidate2;  
     }  
   }  
 };  

169 Majority Element I

来源:Leetcode

原帖:https://leetcode.com/problems/majority-element/

题目:
Given an array of size n, find the majority element.
The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example, For [1, 1, 1, 1, 2, 2, 2], return 1.

代码:
 class Solution {  
 public:  
   int majorityElement(vector<int> &num) {  
     int candidate = 0, count = 0;  
     for (int i = 0; i < num.size(); ++i) {  
       if (count == 0) {  
         candidate = num[i];  
         count++;  
       } else if (candidate == num[i]) {  
         count++;  
       } else {  
         count--;  
       }  
     }  
     return candidate;   
   }  
 };