欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

lintcode-14. First Position of Target

程序员文章站 2022-03-24 17:45:02
...

1. 问题描述

For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.

If the target number does not exist in the array, return -1

2. my solution

2.1 我的思路

看上去像是二分法的变体, 只需要添加几行代码即可, 也就是在相等时再向前遍历, 知道前一个元素不是想要的结果

        while(hi>=lo){
            if(nums[mid] == target){
                while(true){
                    if(mid==0 ||nums[mid-1] != target) return mid;
                    else mid--;
                }
            }

2.2 代码实现


public class Solution {
    /**
     * @param nums: The integer array.
     * @param target: Target to find.
     * @return: The first position of target. Position starts from 0.
     */
    public int binarySearch(int[] nums, int target) {
        // write your code here
        int hi = nums.length-1;
        int lo = 0;
        int mid = hi/2;
        
        while(hi>=lo){
            if(nums[mid] == target){
                while(true){
                    if(mid==0 ||nums[mid-1] != target) return mid;
                    else mid--;
                }
            }
            else if(target > nums[mid])
                lo = mid+1;
            else
                hi = mid-1;
            
            mid = (lo+hi)/2;
            
        }
        return -1;
        
    }
}

2.3 运行结果

可以看到
lintcode-14. First Position of Target

3. others solutions

3.1 思路一(较好)

这种方法记录index , 通过一个res来保存index , 直观简单

class Solution:
    # @param nums: The integer array
    # @param target: Target number to find
    # @return the first position of target in nums, position start from 0 
    def binarySearch(self, nums, target):
        # write your code here
        start = 0; end = len(nums) - 1
        res = -1
        while start <= end:
            mid = start + (end - start) // 2
            if nums[mid] == target:
                res = mid
                end = mid - 1
            elif nums[mid] < target:
                start = mid + 1
            else:
                end = mid - 1
        return res

java

public class Solution {
    /**
     * @param nums: The integer array.
     * @param target: Target to find.
     * @return: The first position of target. Position starts from 0.
     */
    public int binarySearch(int[] nums, int target) {
        // write your code here
        int hi = nums.length-1;
        int lo = 0;
        int res = -1;
        int mid;
        
        while(lo<=hi){
            mid = lo + (hi-lo)/2;
            if(nums[mid] == target){
                res = mid;
                hi = mid - 1;
            }
            else if(target > nums[mid])
                lo = mid+1;
            else
                hi = mid-1;
        }
        return res;
        
    }
}