一.最长连续递增序列
- go语言
func max(a,b int) int{ if a>b{ return a } return b } func findLengthOfLCIS(nums []int) int { n:=len(nums) maxlen:=0 for l:=0;l<n;l++{ r:=l+1 for r<n&&nums[r]>nums[r-1]{ r++ } maxlen=max(r-l,maxlen) } return maxlen }
- cpp
int findLengthOfLCIS(vector<int>& nums) { int n = nums.size(); int maxlen = 0; for (int l = 0; l < n; l++) { int r = l + 1; while (r < n && nums[r] > nums[r - 1]) { r++; } maxlen = max(r - l, maxlen); } return maxlen; }
二.75. 颜色分类
- go
func sortColors(nums []int) { n:=len(nums) n0,n1:=0,0 for i:=0;i<n;i++{ num:=nums[i] nums[i]=2 if num<2{ nums[n1]=1 n1++ } if num<1{ nums[n0]=0 n0++ } } }
- cpp
void sortColors(vector<int>& nums) { int n = nums.size(); int n0 = 0, n1 = 0; for (int i = 0; i < n; i++) { int num = nums[i]; nums[i] = 2; if (num < 2) { nums[n1++] = 1; } if (num < 1) { nums[n0++] = 0; } } }
三. 904. 水果成篮
- go
func max(a, b int) int { if a > b { return a } return b } func totalFruit(nums []int) int { cnt:=map[int]int{} maxlen:=0 l:=0 for r,x:=range(nums){ cnt[x]++ for len(cnt)>2{ y:=nums[l] cnt[y]-- if cnt[y]==0{ delete(cnt,y) } l++ } maxlen=max(maxlen,r-l+1) } return maxlen }
- cpp
class Solution { public: int totalFruit(vector<int>& fruits) { unordered_map<int,int> map; int l=0; int maxlen=0; int n=fruits.size(); for(int r=0;r<n;r++) { map[fruits[r]]++; while(map.size()>2) { auto y=map.find(fruits[l]); y->second--; if(y->second==0) { map.erase(y); } l++; } maxlen=max(maxlen,r-l+1); } return maxlen; } };