标签:fir vector style pre 排序 数字 个性 复杂 遍历数组
统计一个数字在排序数组中出现的次数。
给定一个已经排好序的数组,统计一个数字在数组中出现的次数。
那么最先想到的可以遍历数组统计出现的次数,不过题目给了排序数组,那么一定是利用了排序这个性质来缩减时间复杂度的。
因为如果所给的数字在数组中出现,那么这个数字在数组中一定是连续的,那么可以利用二分查找所给出的数字的首尾索引。
C++
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { if(data.size() == 0){ return 0; } int l = FindFirst(data, k, 0, data.size()-1); int r = FindEnd(data, k, 0, data.size()-1); if(r != -1 && l != -1) return r-l+1; else return 0; } int FindFirst(vector<int> &data ,int k, int left, int right){ if(left > right) return -1; int mid = left + (right - left) / 2; if(data[mid] == k){ if((mid > 0 && data[mid-1] != k) || mid == 0) return mid; else right = mid - 1; } else if(data[mid] < k){ left = mid + 1; } else{ right = mid -1; } return FindFirst(data, k, left, right); } int FindEnd(vector<int> &data ,int k, int left, int right){ if(left > right) return -1; int mid = left + (right - left) / 2; if(data[mid] == k){ if((mid < data.size()-1 && data[mid+1] != k) || mid == data.size()-1) return mid; else left = mid + 1; } else if(data[mid] < k){ left = mid + 1; } else{ right = mid -1; } return FindEnd(data, k, left, right); } };
Java
public class Solution { public int GetNumberOfK(int [] array , int k) { if(array.length == 0){ return 0; } int l = FindFirst(array, k, 0, array.length-1); int r = FindEnd(array, k, 0, array.length-1); if(r != -1 && l != -1) return r-l+1; else return 0; } int FindFirst(int [] array ,int k, int left, int right){ if(left > right) return -1; int mid = left + (right - left) / 2; if(array[mid] == k){ if((mid > 0 && array[mid-1] != k) || mid == 0) return mid; else right = mid - 1; } else if(array[mid] < k){ left = mid + 1; } else{ right = mid -1; } return FindFirst(array, k, left, right); } int FindEnd(int [] array ,int k, int left, int right){ if(left > right) return -1; int mid = left + (right - left) / 2; if(array[mid] == k){ if((mid < array.length-1 && array[mid+1] != k) || mid == array.length-1) return mid; else left = mid + 1; } else if(array[mid] < k){ left = mid + 1; } else{ right = mid -1; } return FindEnd(array, k, left, right); } }
剑指Offer-36.数字在排序数组中出现的次数(C++/Java)
标签:fir vector style pre 排序 数字 个性 复杂 遍历数组
原文地址:https://www.cnblogs.com/silentteller/p/12019837.html