首页 > 试题广场 >

在升序数组中查找元素的位置

[编程题]在升序数组中查找元素的位置
  • 热度指数:1132 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个长度为n的非降序排列的整数数组nums,和一个目标值 target。请找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]
该题有的解法


示例1

输入

[4,7,7,8,8,10],8

输出

[3,4]

说明

可以在数组中找到整数8,其开始位置为3,结束位置为4     
示例2

输入

[4,7,7,8,8,10],6

输出

[-1,-1]

说明

不可以在数组中找到整数6,故输出整数-1     
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param nums int整型ArrayList
     * @param target int整型
     * @return int整型ArrayList
     */
    public ArrayList<Integer> searchRange (ArrayList<Integer> nums, int target) {
        // write code here
        int[] res = new int[2];
        ArrayList<Integer> result = new ArrayList<>();
        if (nums.size() == 0) {
            result.add(-1);
            result.add(-1);
            return result;
        }
        int left = 0;
        int right = nums.size() - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums.get(mid) >= target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        if (left >= nums.size() || nums.get(left) != target) {
            result.add(-1);
            result.add(-1);
            return result;
        }
        res[0] = left;
        left = 0;
        right = nums.size() - 1;
        while (left <= right) {
            int mid = (left + right + 1) / 2;
            if (nums.get(mid) <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        res[1] = right;
        for(int i = 0; i < 1; i++){
            result.add(res[i]);
        }
        return result;
    }
}

发表于 2025-01-02 22:18:58 回复(0)

问题信息

难度:
1条回答 1808浏览

热门推荐

通过挑战的用户

查看代码
在升序数组中查找元素的位置