NC74. 数字在升序数组中出现的次数
描述
示例1
输入:
[1,2,3,3,3,3,4,5],3
输出:
4
示例2
输入:
[1,3,4,5],6
输出:
0
C 解法, 执行用时: 2ms, 内存消耗: 324KB, 提交时间: 2021-06-06
/** * * @param data int整型一维数组 * @param dataLen int data数组长度 * @param k int整型 * @return int整型 */ int bin_serch(const int* data, int dataLen, int k) { int left=0; int right=dataLen-1; while(left<right) { int avarage=(left+right)/2; if(k==data[avarage])return avarage; else if(k>data[avarage]) { left=avarage+1; } else { right=avarage-1; } } return -1; } int GetNumberOfK(int* data, int dataLen, int k ) { //int different=0; int count=0; int left=bin_serch(data,dataLen, k) ; int right=left+1; while(data[left]==k&&left>=0) { count++; left--; } while(data[right]==k&&right<dataLen) { count++; right++; } return count; // write code here }
C++ 解法, 执行用时: 2ms, 内存消耗: 352KB, 提交时间: 2021-04-25
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { int lbound = 0, rbound = 0; // 二分找到上届和下届 // 找下届 int left = 0; int right = data.size(); int p1; while(left < right) { p1 = (left + right) / 2; if (data[p1] >= k) // 往左侧 right = p1; else // 右侧 left = p1+1; } lbound = left; // 找下届 left = 0; right = data.size(); int p2; while(left < right) { p2 = (left + right) / 2; if (data[p2] > k) // 往左侧 right = p2; else // 右侧 left = p2+1; } rbound = left; // if (data[p1] != k) // return 0; return rbound - lbound; } };
C 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-06-09
/** * * @param data int整型一维数组 * @param dataLen int data数组长度 * @param k int整型 * @return int整型 */ int GetNumberOfK(int* data, int dataLen, int k ) { int count =0; for(int i = 0;i<dataLen;i++) { if (*(data+i) == k) count+=1; } return count; // write code here }
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-05-25
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { if(k<data[0]) return 0; int num=0; for(int i=0;i<data.size();i++) { if(k==data[i]) { num++; } else if(k<data[i]) break; } return num; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-05-19
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { int l=0,r = data.size()-1; int flag=0; int mid; while(l<=r){ mid = (r-l)/2+l; if(data[mid]>k){ r = mid-1; }else if(data[mid]<k){ l = mid+1; }else if(data[mid]==k){ flag=1; break; } } if(flag==0) return 0; int j = mid-1,i = mid +1; while((j>=0&&data[j]==k)||(i<=data.size()-1&&data[i]==k)){ if(j>=0&&data[j]==k){ flag++; j--; } if(i<=data.size()-1&&data[i]==k){ flag++; i++; } } return flag; } };