[34] power button LeetCode find elements in a sorted array in the first and last position

Disclaimer: This article is original blog without permission, please do not reprint. https://blog.csdn.net/u013095333/article/details/91432667

Subject description (in difficulty)

Nums Given an array of integers arranged in ascending order, according to the target and one target value. Identify a given target start and end positions in the array.

Your time complexity of the algorithm must be O (log n) level.

If the target is not present in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1, -1]

link

https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/

Thinking

Binary search, binary search to improve
first find the first one to find elements. Ordinary binary search to find the elements on the end, the improved binary search to find the elements, and to meet this element is either the first element of the array or the previous element is smaller than the element that note is to be searched first elements, before terminating this case. Otherwise, you can follow the normal binary search routine.
Find the last element, the same process, but the elements required to meet the conditions were changed to either the last element of the array, or after an element is larger than the found elements.
Twice, the first time to find a time to find the last one, can be a little pruning.

Code

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int ansStart = -1;
        int ansEnd = -1;
        vector<int> ans;
        int start = 0;
        int end = nums.size() - 1;
        int mid = (start + end) / 2;
		while(start <= end){
        	mid = (start + end) / 2;
			if(nums[mid] == target){
				if(mid == 0 || nums[mid-1] < target){
					ansStart = mid;
					break;
				}
				else{
					end = mid - 1;
				}
			}
			else if(nums[mid] > target){
				end = mid - 1;
			}
			else{
				start = mid + 1;
			}
        }
        if(ansStart >= 0){
        	start = ansStart;
        	end = nums.size() - 1;
        	while(start <= end){
        		mid = (start + end) / 2;
        		if(nums[mid] == target){
        			if(mid == nums.size() - 1 || nums[mid+1] > target){
        				ansEnd = mid;
        				break;
        			}
        			else{
        				start = mid + 1;
        			}
        		}
        		else if(nums[mid] > target){
        			end = mid - 1;
        		}
        		else{
        			start = mid + 1;
        		}
        	}
        }
        ans.push_back(ansStart);
        ans.push_back(ansEnd);
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/u013095333/article/details/91432667