• 34. 在排序数组中查找元素的第一个和最后一个位置


    给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

    如果数组中不存在目标值 target,返回 [-1, -1]。

    进阶:

    你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
     

    示例 1:

    输入:nums = [5,7,7,8,8,10], target = 8
    输出:[3,4]
    示例 2:

    输入:nums = [5,7,7,8,8,10], target = 6
    输出:[-1,-1]
    示例 3:

    输入:nums = [], target = 0
    输出:[-1,-1]

    #include<iostream>
    #include<stack>
    #include<algorithm>
    #include<string>
    #include<vector>
    using namespace std;
    /*
    先使用二分查找法,
    找出其中一个目标值的位置,递归调用搜索到中间值;
    然后向两边搜索找出起始和结束的位置;
    */
    class Solution {
    public:
    	vector<int> searchleftandright(vector<int>& nums, int target) 
    	{
    		int idx = search(nums, 0, nums.size() - 1, target);
    		if (idx == -1)
    		{
    			return{ -1, -1 };
    		}
    		int left = idx, right = idx;
    		while (left > 0 && nums[left - 1] == nums[idx])
    		{
    			--left;
    		}
    		while (right < nums.size() - 1 && nums[right + 1] == nums[idx])
    		{
    			++right;
    		}
    		return{ left, right };
    	}
    	int search(vector<int>& nums, int left, int right, int target) 
    	{
    		if (left > right)
    		{
    			return -1;
    		}
    		int mid = left + (right - left) / 2;
    		if (nums[mid] == target)
    		{
    			return mid;
    		}
    		if (nums[mid] < target)
    		{
    			return search(nums, mid + 1, right, target);
    		}
    		else
    		{
    			return search(nums, left, mid - 1, target);
    		}
    	}
    };
    
    int main()
    {
    	int a[1000];
    	int x;
    	int i = 0;
    	vector<int> vec;
    	vector<int> ans;
    	int target;
    	while (cin >> a[i])
    	{
    
    		vec.push_back(a[i]);
    		i++;
    		x = cin.get();
    		if (x == '
    ')
    			break;
    
    	}
    	cin >> target;
    	ans = Solution().searchleftandright(vec, target);
    	cout << ans[0] << " " << ans[1] << endl;
    	system("pause");
    	return 0;
    }
    

      

  • 相关阅读:
    解决MySQL报错:1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'informat
    安装KubeSphere
    kubesphere 安装
    正则表达式在线测试
    爬虫与Python:(二)Python基础篇——扩展:实现九九乘法表
    为什么 Python 的 Range 要设计成左开右闭区间?
    Python内置函数之range()
    爬虫与Python:(二)Python基础篇——13.类
    爬虫与Python:(二)Python基础篇——12.函数
    CSS之text-align
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/14860666.html
Copyright © 2020-2023  润新知