zoukankan      html  css  js  c++  java
  • [LintCode] 14 First Position of Target

    Description
    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.


    Example
    If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.


    Challenge
    If the count of numbers is bigger than 2^32, can your code work properly?

    4/26/2017

    算法班

    不是很明白challenge说数字大于2^32的意思,二分法是合理的吗?

     1 class Solution {
     2     /**
     3      * @param nums: The integer array.
     4      * @param target: Target to find.
     5      * @return: The first position of target. Position starts from 0.
     6      */
     7     public int binarySearch(int[] nums, int target) {
     8         //write your code here
     9         if (nums == null || nums.length == 0) return -1;
    10         if (target > nums[nums.length - 1] || target < nums[0]) return -1;
    11         
    12         int start = 0, end = nums.length - 1;
    13         while (start + 1 < end) {
    14             int mid = start + (end - start) / 2;
    15             if (nums[mid] >= target) {
    16                 end = mid;
    17             } else {
    18                 start = mid;  // to find the first position, we need to include target in the search range
    19             }
    20         }
    21         
    22         if (nums[start] == target) return start;
    23         else if (nums[end] == target) return end;
    24         return -1;
    25     }
    26 }
  • 相关阅读:
    Linux 中国镜像
    VMWare 安装 Debian 9
    Linux 安装Docker compose 快速方法
    Nginx on Docker 配置
    Docker 中配置Nginx
    Nginx IPV4 问题
    VMWare中CentOS 7 配置 XShell连接
    在CentOS 7 中安装Docker
    Docker for Windows 和虚拟机VMWare共存方案
    Nginx 配置多个站点
  • 原文地址:https://www.cnblogs.com/panini/p/6770516.html
Copyright © 2011-2022 走看看