• Classical Binary Search


    Find any position of a target number in a sorted array. Return -1 if target does not exist.

    与题目 First Position of Target 相同
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    public class Solution {
        /**
         * @param nums: An integer array sorted in ascending order
         * @param target: An integer
         * @return an integer
         */
        public int findPosition(int[] nums, int target) {
            // Write your code here
            if(nums == null || nums.length == 0)return -1;
            int left = 0, right = nums.length - 1;
            while(left < right){
                int mid = left + (right - left) / 2;
                if(nums[mid] < target)
                    left = mid + 1;
                else
                    right = mid;
            }
            if(nums[right] == target)
                return right;
            return -1;
        }
    }





  • 相关阅读:
    架构笔记七
    架构笔记六
    架构笔记五
    架构笔记四
    python2与python3的区别
    萌新VRTK学习(四)攀爬系统
    萌新VRTK学习(三)物体的抓取
    萌新VRTK学习(二)移动
    萌新VRTK学习(一)VRTK的配置
    C#委托事件随笔
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/b40a2a8739a00d055d248b35db5a0cb8.html
Copyright © 2020-2023  润新知