• 面试题38 数字在排序数组中出现的次数


    题目描述

    统计一个数字在排序数组中出现的次数。
     1 class Solution {
     2 public:
     3     int getFirstK(vector<int> data ,int k){
     4         int low = 0, high = data.size() - 1, mid;
     5         while (low <= high){
     6             mid = (low + high) / 2;
     7             if ((mid > 0 && data[mid] == k && data[mid - 1] != k) || data[mid] == k && mid == 0)
     8                 return mid;
     9             else if (data[mid] > k || data[mid - 1] == k)
    10                 high = mid - 1;
    11             else
    12                 low = mid + 1;
    13         }
    14         return -1;
    15     }
    16     
    17     int getLastK(vector<int> data ,int k){
    18         int low = 0, high = data.size() - 1, mid;
    19         while (low <= high){
    20             mid = (low + high) / 2;
    21             if ((mid < data.size() - 1 && data[mid] == k && data[mid + 1] != k) || data[mid] == k && mid == data.size() - 1)
    22                 return mid;
    23             else if (data[mid] < k || data[mid + 1] == k)
    24                 low = mid + 1;
    25             else
    26                 high = mid - 1;
    27         }
    28         return -1;
    29     }
    30     
    31     int GetNumberOfK(vector<int> data ,int k) {
    32         int num = 0, length = data.size();
    33         if (length == 0)
    34             return num;
    35         int first = getFirstK(data ,k);
    36         int last = getLastK(data ,k); 
    37         
    38         if (first > -1 && last > -1)
    39             num = last - first + 1;
    40         return num;
    41     }
    42 };
  • 相关阅读:
    20161203
    20161201
    20161128课堂笔记
    数组排序 (选择排序、冒泡排序、插入排序、希尔排序)
    编一个多用户登陆程序
    20161115课堂笔记
    20161114课堂笔记
    20161111课堂笔记
    面试常见问题
    java 基础第一周
  • 原文地址:https://www.cnblogs.com/wanderingzj/p/5358775.html
Copyright © 2020-2023  润新知