Algorithm: Find the position of an element

Problem Description

Find the first and last positions of the element in the sorted array.
Given an integer array nums in ascending order, and a target value target. Find the start and end positions of the given target value in the array.
The time complexity of your algorithm must be O(log n) level.
If there is no target value 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]

solution

First, this method is a good way to think about regardless of the space complexity. After traversing the array and finding the target, it is judged whether it is the first time it appears, instead of putting it in a later position. But the problem requires the space complexity to be O(log n), this method has too many cycles, which is obviously wrong.
Second, we can notice that the title says that it is an ascending array. It is not difficult to think of an ascending array at will.

Code

        int[] nums = {
    
    5,7,7,8,8,10};
        int[] a = {
    
    -1,-1};
        int target = 8;
        //方法1
        for (int i=0;i<nums.length;i++){
    
    
            if(nums[i]==target){
    
    
                if (a[0]==-1){
    
    
                    a[0] = i;
                }else{
    
    
                    a[1] = i;
                }
            }
        }
        for (Integer i:a) {
    
    
            System.out.println(i);
        }

		//方法2
        int left = 0;
        int right = nums.length-1;
        while(left<=right){
    
    
            int mid = (left + right)/2;
            if(nums[mid]==target){
    
    
                while(mid>=left && nums[mid]==target){
    
    
                    mid--;
                }
                a[0] = mid+1;
                mid = (left + right)/2;
                while(mid<=right && nums[mid]==target){
    
    
                    mid++;
                }
                a[1] = mid - 1;
                break;
            }else if (nums[mid] > target){
    
    
                right = mid-1;
            }else{
    
    
                left = mid+1;
            }
        }
        for (Integer i:a) {
    
    
            System.out.println(i);
        }

to sum up

Through the comparison between Method 1 and Method 2, it is not difficult to find that the code using dichotomy is really long, but Method 2 satisfies the space complexity requirements in the topic.

Guess you like

Origin blog.csdn.net/weixin_46687295/article/details/106450328