数字在排序数组中出现的次数/leetcode 34. 在排序数组中查找元素的第一个和最后一个位置

1.二分查找的扩展,牛客网Ac,数字在排序数组中出现的次数

c++ code:

class Solution {
public:/*二分查找的扩展,确定最左边和最右边即可*/
	int FindLeft(vector<int> data, int k)
	{
		int flag = 0;
		int begin = 0, end = data.size() - 1;
		while (begin <= end)
		{
			int mid = (begin + end) / 2;
			if (data[mid] < k)
				begin = mid + 1;
			else if (data[mid]>k)
				end = mid - 1;
			else
			{
				flag = 1;//标记数组中存在k
				if (mid>0&&data[mid - 1] == k)
					end = mid - 1;//继续向左边逼近
				else
					return mid;
			}
		}
		if (flag)
			return begin;
		else
			return -1;
	}
	int FindRight(vector<int> data, int k)
	{
		int begin = 0, end = data.size() - 1;
		int flag = 0;
		while (begin <= end)
		{
			int mid = (begin + end) / 2;
			if (data[mid] < k)
				begin = mid + 1;
			else if (data[mid]>k)
				end = mid - 1;
			else
			{
				flag = 1;
				if ((mid < data.size()-1)&&data[mid + 1] == k)
					begin = mid + 1;
				else
					return mid;
			}
		}
		if (flag)
			return end;
		else
			return -1;
	}
	int GetNumberOfK(vector<int> data, int k) {
		int left = FindLeft(data,k);
		int right =FindRight(data,k) ;
		if (left == -1 && right == -1)return 0;
		return right - left + 1;
	}
};
34. 在排序数组中查找元素的第一个和最后一个位置

本题就是二分查找的变形,我记得和之前的一个剑指offer题在排序数组中查找元素的出现的次数其实一样。https://blog.csdn.net/dongyanwen6036/article/details/84863703
如果没查找到,返回-1.
97% AC leetcode C++:

class Solution {
public:
	int FindLeft(vector<int>& nums, int target)
	{
		int low = 0, high = nums.size() - 1;		 
		while (low <= high)
		{
			int mid = (low + high) / 2;
			if (nums[mid] > target)
				high = mid - 1;
			else if (nums[mid] < target)
				low = mid + 1;
			else
			{
				 
				if (mid > 0 && nums[mid - 1] == target)
					high = mid - 1;
				else
					return mid;
			}
		}
		return  -1; 
	}
	int FindRight(vector<int>& nums, int target)
	{
		int low = 0, high = nums.size() - 1;
		while (low <= high)
		{
			int mid = (low + high) / 2;
			if (nums[mid] > target)
				high = mid - 1;
			else if (nums[mid] < target)
				low = mid + 1;
			else
			{

				if (mid < nums.size()-1 && nums[mid + 1] == target)
				     low = mid + 1;
				else
					return mid;
			}
		}
		return  -1;
	}
	vector<int> searchRange(vector<int>& nums, int target) {
		int Left = FindLeft(nums,target);
		int Right = FindRight(nums,target);
		vector<int> res;
		res.push_back(Left);
		res.push_back(Right);
		return res;
	}
};

你可能感兴趣的:(剑指offer题,leetcode题,剑指offer,leetcode)