Cattle off network - often prove safety office- number that appears in the sort array

Title: The number of times a statistical number that appears in the sort array.
Solution one:
idea: violent solution. Iterate over the array, count the number of times that number appears.

class Solution {
public:
    int GetNumberOfK(vector<int> data ,int k) {
        int count = 0;
        for (int i= 0;i<data.size();++i)
        {
            if(data[i]==k)
                count++;
        }
        return count;
    }
};

Solution two:
thinking: twice dichotomy, respectively, to determine the beginning and end numbers appear. For the poor is the answer.

class Solution {
public:
	int GetNumberOfK(vector<int> data, int k) {
		int l = 0;
		int r = data.size();
		while (l < r)
		{
			int mid = (l + r) / 2;
			if (data[mid] < k) l = mid + 1;
			else
				r = mid;
		}
		int left = l;
		l = 0;
		r = data.size();
		while (l < r)
		{
			int mid = (l + r) / 2;
			if (data[mid] > k) r=mid;
			else
				l = mid+1;
		}
		return r-left;
	}
};

The python Solution:
Violence Act:

# -*- coding:utf-8 -*-
class Solution:
    def GetNumberOfK(self, data, k):
        # write code here
        count = 0
        for num in data:
            if num == k:
                count += 1
        return count

Guess you like

Origin blog.csdn.net/qq_43387999/article/details/91126657