Problem
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.
ExampleIf the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.
challengeIf the count of numbers is bigger than 2^32, can your code work properly?
Notewhile (start + 1 < end)
+1 guaranteed that there always exists mid.
In the for loop, the else branch is actually when num[mid] >= target, why? Because this ensures that the mid pointer goes to the former ones if target is right in the middle.
class Solution { public int binarySearch(int[] nums, int target) { //write your code here if (nums == null || nums.length < 1) { return -1; } int len = nums.length; int start = 0, end = len - 1; while (start + 1 < end) { //for the challenge: avoid overflow int mid = start + (end - start) / 2; if (nums[mid] < target) { start = mid; } else { end = mid; } } //after the while loop, only num[start] and num[end] left. //so just discuss them if (nums[start] == target) { return start; } if (nums[end] == target) { return end; } return -1; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.specialneedsforspecialkids.com/yun/65482.html
摘要:首先,建立二元結(jié)果數(shù)組,起點(diǎn),終點(diǎn)。二分法求左邊界當(dāng)中點(diǎn)小于,移向中點(diǎn),否則移向中點(diǎn)先判斷起點(diǎn),再判斷終點(diǎn)是否等于,如果是,賦值給。 Problem Given a sorted array of n integers, find the starting and ending position of a given target value. If the target is not...
Problem For a given source string and a target string, you should output the first index(from 0) of target string in source string. If target does not exist in source, just return -1. Note 我終于找到了比較好的K...
摘要:建立動(dòng)規(guī)數(shù)組,表示從起點(diǎn)處到達(dá)該點(diǎn)的可能性。循環(huán)結(jié)束后,數(shù)組對(duì)所有點(diǎn)作為終點(diǎn)的可能性都進(jìn)行了賦值。和的不同在于找到最少的步數(shù)。此時(shí)的一定是滿足條件的最小的,所以一定是最優(yōu)解。 Jump Game Problem Given an array of non-negative integers, you are initially positioned at the first index...
Problem Xiao Ming is going to help companies buy fruit. Give a codeList, which is loaded with the fruit he bought. Give a shoppingCart, which is loaded with target fruit. We need to check if the order...
Problem Implement a trie with insert, search, and startsWith methods. Example insert(lintcode) search(code) // return false startsWith(lint) // return true startsWith(linterror) // return false insert...
閱讀 640·2021-08-17 10:15
閱讀 1724·2021-07-30 14:57
閱讀 1978·2019-08-30 15:55
閱讀 2820·2019-08-30 15:55
閱讀 2708·2019-08-30 15:44
閱讀 670·2019-08-30 14:13
閱讀 2386·2019-08-30 13:55
閱讀 2592·2019-08-26 13:56