1. 程式人生 > >Leetcode-904 水果成籃

Leetcode-904 水果成籃

clas nbsp solution () auto end code 水果 return

 1 class Solution
 2 {
 3     public:
 4         int totalFruit(vector<int>& tree)
 5         {
 6             vector<pair<int,int>> dealList;
 7             int curType = tree[0];
 8             int curSum = 1;
 9             for(int i = 1; i < tree.size(); i ++)
10             {
11 if(tree[i]==curType) 12 curSum ++; 13 else 14 { 15 dealList.push_back(make_pair(curType,curSum)); 16 curSum = 1; 17 curType = tree[i]; 18 } 19 }
20 dealList.push_back(make_pair(curType,curSum)); 21 22 // for(auto d:dealList) 23 // cout << d.first << " " << d.second << endl; 24 // cout << endl; 25 26 int result = dealList[0].second; 27 int max = 1
; 28 int typeA = dealList[0].first,typeB = -1; 29 int justI; 30 for(int i = 1; i < dealList.size(); i ++) 31 { 32 if(dealList[i].first != typeA && typeB == -1) 33 { 34 typeB = dealList[i].first; 35 result += dealList[i].second; 36 justI = i; 37 //cout << dealList[i].first << endl; 38 } 39 else if(dealList[i].first == typeA || dealList[i].first==typeB) 40 { 41 result += dealList[i].second; 42 // cout << dealList[i].first << endl; 43 } 44 else if(dealList[i].first != typeA && dealList[i].first != typeB) 45 { 46 // cout << dealList[i].first << endl; 47 result = dealList[justI].second; 48 i = justI; 49 typeB = -1; 50 typeA = dealList[justI].first; 51 } 52 // cout << dealList[i].first << endl; 53 if(result > max) 54 max = result; 55 } 56 if(result > max) 57 max = result; 58 return max; 59 } 60 };

Leetcode-904 水果成籃