自己的写法
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { int length = data.size(); if(length <= 0) return 0; for(int i = 0;i < length;i++){ } int index1 = GetFirst(data,k,0,length-1); int index2 = GetLast(data,k,0,length-1); return exit(data,k) ? (index2-index1+1) : 0; } int GetFirst(vector<int> data,int k,int start,int end){ if(start == end) return start; int first = 0; int mid = (start+end)/2; if(data[mid] == k){ if(data[mid-1] != k) return mid; else first = GetFirst(data,k,start,mid-1); } else if(data[mid] < k) first = GetFirst(data,k,mid+1,end); else first = GetFirst(data,k,start,mid-1); return first; } int GetLast(vector<int> data,int k,int start,int end){ if(start == end) return start; int last = end; int mid = (start+end)/2; if(data[mid] == k){ if(data[mid+1] != k) return mid; else last = GetLast(data,k,mid+1,end); } else if(data[mid] < k) last = GetLast(data,k,mid+1,end); else last = GetLast(data,k,start,mid-1); return last; } bool exit(vector<int> data,int k){ int length = data.size(); int i = 0; for(;i < length;i++){ if(data[i] == k) return true; } return false; } };
更简洁的代码
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { if(data.empty() || k <= 0) return 0; int FirstK = GetFirstK(data,k,0,data.size()-1); int LastK = GetLastK(data,k,0,data.size()-1); if(FirstK > -1 && LastK > -1) return LastK - FirstK + 1; else return 0; } int GetFirstK(vector<int> data,int k,int start,int end){ if(start > end) return -1; int mid = (end + start)/2; if(data[mid] == k){ if(data[mid-1] == k) end = mid - 1; else return mid; } else if(data[mid] > k) end = mid - 1; else if(data[mid] < k) start = mid + 1; return GetFirstK(data,k,start,end); } int GetLastK(vector<int> data,int k,int start,int end){ if(start > end) return -1; int mid = (end + start)/2; if(data[mid] == k){ if(data[mid+1] == k) start = mid + 1; else return mid; } else if(data[mid] > k) end = mid - 1; else if(data[mid] < k) start = mid + 1; return GetLastK(data,k,start,end); } };
时间: 2024-10-12 21:26:28