34在排序数组中查找元素的第一个和最后一个位置-hot100-java题解

这个题和33搜索旋转排序数组都是类似的题目。

一、问题描述:

* 34在排序数组中查找元素的第一个和最后一个位置
* 给你一个按照非递减顺序排列的整数数组 nums,和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
* 如果数组中不存在目标值 target,返回 [-1, -1]。你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。
* 示例 1:   输入:nums = [5,7,7,8,8,10], target = 8    输出:[3,4]
* 示例 2:   输入:nums = [5,7,7,8,8,10], target = 6     输出:[-1,-1]
* 示例 3:   输入:nums = [], target = 0    输出:[-1,-1]
* 提示:     0 <= nums.length <= 105  -109 <= nums[i] <= 109   nums 是一个非递减数组   -109 <= target <= 109

二、题解

很直接明了了,对于题目的意思真的很简单。对于只有1个索引对应的元素等于target,那么开始和结束位置都是这个索引。

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int i = 0;
        int[] myRes = new int[2];
        myRes[0] = -1;
        myRes[1] = -1;

        for (; i < nums.length; i++) {
            if (nums[i] == target) {
                myRes[0] = i;
                break;
            }
        }
        for (; i < nums.length && nums[i] == target; i++) myRes[1] = i;
        return myRes;
    }

}

本地测试:

@Test
public void testSolution() {
    int[][] arr = {
            {5,7,7,8,8,10},
            {5,7,7,8,8,10},
            {},
    };
    int[] targets = {
            8,
            6,
            0,
    };
    for (int i = 0; i < arr.length; i++) {
        System.out.println(Arrays.toString(arr[i]) + "` result is " + Arrays.toString(searchRange(arr[i], targets[i])));
    }
}

本地模拟acm模式:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String[] split = scanner.nextLine().split(",");
    int[] nums = new int[split.length];
    for (int i = 0; i < split.length; i++) nums[i] = Integer.parseInt(split[i]);
    String sInt = scanner.nextLine();
    int target = Integer.parseInt(sInt);
    Solution solution = new Solution();
    int[] ints = solution.searchRange(nums, target);
    System.out.println(Arrays.toString(ints));
}

你可能感兴趣的:(java,算法,数据结构,hot100,leetcode)