摘要:首先,建立二元結(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 found in the array, return [-1, -1].
ExampleGiven [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
O(log n) time.
Note首先,建立二元結(jié)果數(shù)組res,起點(diǎn)start,終點(diǎn)end。
二分法求左邊界:
當(dāng)中點(diǎn)小于target,start移向中點(diǎn),否則end移向中點(diǎn);
先判斷起點(diǎn),再判斷終點(diǎn)是否等于target,如果是,賦值給res[0]。
二分法求右邊界:
當(dāng)中點(diǎn)大于target,end移向中點(diǎn),否則start移向中點(diǎn);
先判斷終點(diǎn),再判斷起點(diǎn)是否等于target,如果是,賦值給res[1]。
返回res。
public class Solution { public int[] searchRange(int[] A, int target) { int []res = {-1, -1}; if (A == null || A.length == 0) return res; int start = 0, end = A.length - 1; int mid; while (start + 1 < end) { mid = start + (end - start) / 2; if (A[mid] < target) start = mid; else end = mid; } if (A[start] == target) res[0] = start; else if (A[end] == target) res[0] = end; else return res; start = 0; end = A.length - 1; while (start + 1 < end) { mid = start + (end - start) / 2; if (A[mid] > target) end = mid; else start = mid; } if (A[end] == target) res[1] = end; else if (A[start] == target) res[1] = start; else return res; return res; } }Another Binary Search Method
public class Solution { public int[] searchRange(int[] nums, int target) { int n = nums.length; int[] res = {-1, -1}; int start = 0, end = n-1; while (nums[start] < nums[end]) { int mid = start + (end - start) / 2; if (nums[mid] > target) end = mid - 1; else if (nums[mid] < target) start = mid + 1; else { if (nums[start] < target) start++; if (nums[end] > target) end--; } } if (nums[start] == target) { res[0] = start; res[1] = end; } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/65938.html