zoukankan      html  css  js  c++  java
  • NC105 二分查找-II

    package NC;

    /**
    * NC105 二分查找-II
    *
    * 请实现有重复数字的升序数组的二分查找
    * 给定一个 元素有序的(升序)整型数组 nums 和一个目标值 target ,
    * 写一个函数搜索 nums 中的第一个出现的target,如果目标值存在返回下标,否则返回 -1
    *
    * @author TANG
    * @date 2021/9/27
    */
    public class BinarySearch {


    public int search (int[] nums, int target) {
    // write code here
    if(nums.length == 0) {
    return -1;
    }


    int begin = 0;
    int end = nums.length - 1;
    int result = -1;
    while(begin <= end) {
    int mid = (end + begin) / 2;
    if(nums[mid] == target) {
    //找到目标值
    result = mid;
    break;
    }
    if(nums[mid] > target) {
    end = mid - 1;
    }else {
    begin = mid + 1;
    }
    }

    if(result < 0) {
    return result;
    }

    //找到最靠前的result
    while(nums[result] == target) {
    if(result > 0 && nums[result - 1] == target) {
    result--;
    }else {
    break;
    }
    }

    return result;
    }

    public static void main(String[] args) {
    int[] num = {-2};

    System.out.println(new BinarySearch().search(num, -3));

    }


    }
  • 相关阅读:
    利用dockerfile定制镜像
    发布Docker 镜像到dockerhub
    Docker 停止容器
    133. Clone Graph
    132. Palindrome Partitioning II
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    127. Word Ladder
  • 原文地址:https://www.cnblogs.com/ttaall/p/15342028.html
Copyright © 2011-2022 走看看