摘要:首先,建立二元結果數組,起點,終點。二分法求左邊界當中點小于,移向中點,否則移向中點先判斷起點,再判斷終點是否等于,如果是,賦值給。
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首先,建立二元結果數組res,起點start,終點end。
二分法求左邊界:
當中點小于target,start移向中點,否則end移向中點;
先判斷起點,再判斷終點是否等于target,如果是,賦值給res[0]。
二分法求右邊界:
當中點大于target,end移向中點,否則start移向中點;
先判斷終點,再判斷起點是否等于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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/65938.html
摘要:兩種方法,轉置鏡像法和公式法。首先看轉置鏡像法原矩陣為轉置后水平鏡像翻轉后所以,基本的思路是兩次遍歷,第一次轉置,第二次水平鏡像翻轉變換列坐標。公式法是應用了一個翻轉的公式如此翻轉四次即可。二者均可,并無分別。 Problem You are given an n x n 2D matrix representing an image.Rotate the image by 90 de...
摘要:找中點若起點小于中點,說明左半段沒有旋轉,否則說明右半段沒有旋轉。在左右半段分別進行二分法的操作。只判斷有無,就容易了。還是用二分法優化 Search in Rotated Sorted Array Problem Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 ...
摘要:首先,我們應該了解字典樹的性質和結構,就會很容易實現要求的三個相似的功能插入,查找,前綴查找。既然叫做字典樹,它一定具有順序存放個字母的性質。所以,在字典樹的里面,添加,和三個參數。 Problem Implement a trie with insert, search, and startsWith methods. Notice You may assume that all i...
摘要:遞歸左右子樹,若左右子樹都有解,那么返回根節點若僅左子樹有解,返回左子樹若僅右子樹有解,返回右子樹若都無解,返回。對于而言,更為簡單公共祖先一定是大于等于其中一個結點,小于等于另一個結點。 Problem Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the ...
摘要:保證高的小朋友拿到的糖果更多,我們建立一個分糖果數組。首先,分析邊界條件如果沒有小朋友,或者只有一個小朋友,分別對應沒有糖果,和有一個糖果。排排坐,吃果果。先往右,再往左。右邊高,多一個??偤图由闲∨笥芽倲?,就是要準備糖果的總數啦。 Problem There are N children standing in a line. Each child is assigned a rat...
閱讀 4620·2021-10-25 09:48
閱讀 3212·2021-09-07 09:59
閱讀 2167·2021-09-06 15:01
閱讀 2693·2021-09-02 15:21
閱讀 2732·2019-08-30 14:14
閱讀 2184·2019-08-29 13:59
閱讀 2514·2019-08-29 11:02
閱讀 2533·2019-08-26 13:33