面试刷题偶有记录

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

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

你的算法时间复杂度必须是 O(log n) 级别。

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

示例:输入: nums = [5,7,7,8,8,10], target = 8

输出: [3,4]

​
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int left = searchRangeLeft(nums, target);
        int right = searchRangeRight(nums, target);
        int[] res = {left, right};
        return res;
    }

    private int searchRangeRight(int[] a, int v){
        int l = 0;
        int r = a.length - 1;
        int res = -1;
        while(l <= r){
            int mid = l + ((r-l)>>1);
            if(a[mid] < v){
                l = mid + 1;
            }else if(a[mid] > v){
                r = mid - 1;
            }else{
                res = mid;
                l = mid + 1;
            }
        }
        return res;
    }
    private int searchRangeLeft(int[] a, int v){
        int l = 0;
        int r = a.length - 1;
        int res = -1;
        while(l <= r){
            int mid = l + ((r-l)>>1);
            if(a[mid] > v){
                r = mid - 1;
            }else if(a[mid] < v){
                l = mid + 1;
            }else{
                res = mid;
                r = mid - 1;
            }
        }
        return res;
    }
}

​

上面这个AC过了,下面这个自己写案例都能过,但是提交显示,代码在下方,求个有缘人帮我看看,谢谢

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int left = searchRangeLeft(nums, target);
        int right = searchRangeRight(nums, target);
        int[] res = {left, right};
        return res;
    }

    public int searchRangeLeft(int[] nums, int target){
        int low = 0;
        int high = nums.length -1;
        int mid;
        while(low<high){
            mid = low+(high-low)/2;
            if(nums[mid] >= target){
                high = mid;
            }else{
                low = mid+1;
            }
        }
        return nums[low]==target?low:-1;
    }

    public int searchRangeRight(int[] nums, int target){
        int low = 0;
        int high = nums.length -1;
        while(low<high){
            int mid = (low+high)/2 + 1;
            if(nums[mid] <= target){
                low = mid;
            }else{
                high = mid-1;
            }
        }
        return nums[low]==target?low:-1;
    }
}

留个坑,后续继续补

 
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页