刷题34. Find First and Last Position of Element in Sorted Array

一、题目说明

题目是34. Find First and Last Position of Element in Sorted Array,查找一个给定值的起止位置,时间复杂度要求是Olog(n)。题目的难度是Medium!

二、我的解答

这个题目还是二分查找(折半查找),稍微变化一下。target==nums[mid]后,需要找前面、后面的值是否=target。

一次写出来,bug free,熟能生巧!怎一个爽字了得!

#include<iostream>
#include<vector>
using namespace std;
class Solution{
	public:
		vector<int> searchRange(vector<int>& nums, int target){
			vector<int> res;
			if(nums.size()<1){
				res.push_back(-1);
				res.push_back(-1);
				return res;
			}
			
			int begin = 0;
			int end = nums.size()-1;
			int mid = -1;
			while(begin <= end){
				mid = (begin + end) / 2; 
				if(nums[mid] == target){
					begin = mid;
					while(begin>0 && nums[begin] == target){
						begin--;
					}
					if(nums[begin]==target){
						res.push_back(begin);
					}else{
						res.push_back(begin+1);
					}
					
					end = mid;
					while(end<nums.size()-1 && nums[end] == target){
						end++;
					}
					if(nums[end]==target){
						res.push_back(end);
					}else{
						res.push_back(end-1);
					}
					return res;
				}else if(nums[mid] < target){
					begin = mid + 1;
				}else{
					end = mid - 1;
				}
			}
			//未找到 
			res.push_back(-1);
			res.push_back(-1);
			return res;
		}
};
int main(){
	Solution s;
	vector<int> nums = {5,7,7,8,8,10};
	vector<int> r = s.searchRange(nums,8);
	for(vector<int>::iterator it=r.begin();it!=r.end();it++){
		cout<<*it<<" ";
	}
	
	r = s.searchRange(nums,6);
	for(int i=0;i<r.size();i++){
		cout<<r[i]<<" ";
	}
	return 0;
} 

代码性能:

Runtime: 12 ms, faster than 38.75% of C++ online submissions for Find First and Last Position of Element in Sorted Array.
Memory Usage: 10.4 MB, less than 70.33% of C++ online submissions for Find First and Last Position of Element in Sorted Array.

三、改进

上一个题目,发现mid = begin + (end - begin) / 2; ,性能比mid = (begin + end) / 2高很多。

性能提高到:

Runtime: 8 ms, faster than 86.11% of C++ online submissions for Find First and Last Position of Element in Sorted Array.
Memory Usage: 10.4 MB, less than 82.42% of C++ online submissions for Find First and Last Position of Element in Sorted Array.

这究竟为何,哪位大神指导,请指点。不胜感激!!!

此处不要提mid = (begin + end) / 2可能溢出。。。

posted @ 2020-02-08 08:47  siwei718  阅读(97)  评论(0编辑  收藏  举报