34. Find First and Last Position of Element in Sorted Array

更新 發佈閱讀 6 分鐘
Spoiler alert—this paragraph contains the answer.

Problem Statement

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.If target is not found in the array, return [-1, -1].You must write an algorithm with `O(log n)` runtime complexity.

Approach

I didn't notice the O(log n) requirement at first, so I used a simple two-pointer method on the sorted array.

  1. Initialize two pointers: left = 0,right = len(nums) - 1. Our goal is to find the first and last indices of target.
  2. Move left forward while nums[left] < target, and move right backward while nums[right] > target to shrink the range.
  3. When nums[left] == target or nums[right] == target, record the candidate first/last positions.
  4. Return [first, last] if found; otherwise return [-1, -1].
NOTE This method is not O(log n) but O(n) in the worst case!

Better Approach (Binary Search)

  1. Use binary search on the sorted array. Compute m = (left + right) // 2 and compare nums[m] with target.
  2. Decide which bound you're looking for: lower bound (first index) or upper bound (last index).
  3. By the time we find nums[m] == target. Now we have find the two boundaries.
[......,7 ,7, 7, 7,........]
Δ Δ
| |
lower upper
  1. For the lower bound:
    • If we alread assume nums[m] == target so next we need to consider whether it is the boundary.
    • If m == left or nums[m - 1] < target, we found the first index (m).
    • Otherwise, move right = m - 1.
  2. For the upper bound:
    • If m == right or nums[m + 1] > target, we found the last index (m). Otherwise, move left = m + 1 and keep searching.

And we need to deal with when num[m] != target

    • If nums[m] < target, move left = m + 1.
    • If nums[m] > target, move right = m - 1.

Continue until left > right. If we never meet the boundary condition, the target doesn't exist.

What can I use this in our life?

Recently I’ve been playing Candy Crush. You match three or more candies in a row or column. Suppose we have five types of candy labeled 1–5, and the board is:

[1, 2, 5, 4, 5, 1, 5, 5, 2, 3, 4, 1, 2, 5, 1, 5]

With one adjacent swap, the goal is to create the longest possible line so you can trigger a stronger effect. After imagining a swap, just check that row or column and read off the first and last index of the same candy to measure the line length.




留言
avatar-img
Ben Yuan的沙龍
0會員
3內容數
學習筆記
你可能也想看
Thumbnail
玉山 Unicard 新戶首刷禮,百大指定消費最高 7.5% 回饋,其中包含日本、韓國、臺灣在地 100 大指定通路,以及國內外旅遊平台、航空公司點數回饋上限1000點。 五大平台每月最高可回饋點數 500 點,今年年底前(12 月底)最後申辦機會,使用期限直達 2026 年 6 月,快把握機會!
Thumbnail
玉山 Unicard 新戶首刷禮,百大指定消費最高 7.5% 回饋,其中包含日本、韓國、臺灣在地 100 大指定通路,以及國內外旅遊平台、航空公司點數回饋上限1000點。 五大平台每月最高可回饋點數 500 點,今年年底前(12 月底)最後申辦機會,使用期限直達 2026 年 6 月,快把握機會!
Thumbnail
許多人為了信用卡優惠,持有大量信用卡,看似精打細算,實則可能浪費時間、造成財務混亂。本文以玉山Unicard為例,探討如何透過整合回饋、簡化選擇,解決多卡族的痛點,實現簡易消費與簡單理財。
Thumbnail
許多人為了信用卡優惠,持有大量信用卡,看似精打細算,實則可能浪費時間、造成財務混亂。本文以玉山Unicard為例,探討如何透過整合回饋、簡化選擇,解決多卡族的痛點,實現簡易消費與簡單理財。
Thumbnail
題目敘述 Combination Sum II_Leetcode #40 給定一個整數陣列candidates 和 目標值target。 每個陣列元素只能選擇一次,請問有多少種組合方法,可以使得組合數總和 = target? 請把滿足組合數總和 = target的組合方法以陣列的形式返回答案
Thumbnail
題目敘述 Combination Sum II_Leetcode #40 給定一個整數陣列candidates 和 目標值target。 每個陣列元素只能選擇一次,請問有多少種組合方法,可以使得組合數總和 = target? 請把滿足組合數總和 = target的組合方法以陣列的形式返回答案
Thumbnail
題目敘述 題目會給定一個二元陣列nums(也就是說,陣列元素只有0,1這兩種情況)。 我們必須從裡面選擇一個元素刪除之後,請問連續為1的最長子陣列的長度是多少? 測試範例 Example 1: Input: nums = [1,1,0,1] Output: 3 Explanation:
Thumbnail
題目敘述 題目會給定一個二元陣列nums(也就是說,陣列元素只有0,1這兩種情況)。 我們必須從裡面選擇一個元素刪除之後,請問連續為1的最長子陣列的長度是多少? 測試範例 Example 1: Input: nums = [1,1,0,1] Output: 3 Explanation:
Thumbnail
題目敘述 題目會給兩個陣列nums1和nums2。 題目要求我們從中同步選擇長度為k的子序列,並且最大化子序列的分數, 回傳最高的分數值。 分數的定義: 分數 = (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] ,
Thumbnail
題目敘述 題目會給兩個陣列nums1和nums2。 題目要求我們從中同步選擇長度為k的子序列,並且最大化子序列的分數, 回傳最高的分數值。 分數的定義: 分數 = (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] ,
Thumbnail
題目敘述 題目會給我們一個輸入整數陣列arr,和一個初始化的刪除次數k? 我們可以任意選擇從arr中刪除k個陣列元素,請問最後留下來的數字,最少會有幾個不同的數字? 註: 最後不同的數字越少越好。 題目的原文敘述 測試範例 Example 1: Input: arr = [5,5
Thumbnail
題目敘述 題目會給我們一個輸入整數陣列arr,和一個初始化的刪除次數k? 我們可以任意選擇從arr中刪除k個陣列元素,請問最後留下來的數字,最少會有幾個不同的數字? 註: 最後不同的數字越少越好。 題目的原文敘述 測試範例 Example 1: Input: arr = [5,5
Thumbnail
題目敘述 題目會給我們一個輸入陣列nums,和一個指定的k值。 請問,在輸入陣列nums中,有幾個子陣列的元素總合恰好為k ? 例如: nums = [1,2,3], k = 3 則有兩個子陣列的元素總合為3,分別是[1,2] 和 [3] 如果是第一次聽到或接觸前綴和prefix的同學
Thumbnail
題目敘述 題目會給我們一個輸入陣列nums,和一個指定的k值。 請問,在輸入陣列nums中,有幾個子陣列的元素總合恰好為k ? 例如: nums = [1,2,3], k = 3 則有兩個子陣列的元素總合為3,分別是[1,2] 和 [3] 如果是第一次聽到或接觸前綴和prefix的同學
Thumbnail
題目敘述 題目會給我們一個輸入陣列nums,每個元素值代表那個格子點可以左右位移的固定長度。 例如,假設 nums[i] = 3,那麼下一步可以移動到nums[i-3] 或 nums[i+3]這兩個格子點。 題目​會給定一個起始點start索引位置,請問我們能不能走到內部數值為0的格子點?
Thumbnail
題目敘述 題目會給我們一個輸入陣列nums,每個元素值代表那個格子點可以左右位移的固定長度。 例如,假設 nums[i] = 3,那麼下一步可以移動到nums[i-3] 或 nums[i+3]這兩個格子點。 題目​會給定一個起始點start索引位置,請問我們能不能走到內部數值為0的格子點?
Thumbnail
題目敘述 題目會給我們一個輸入陣列nums,每個元素值代表那個格子點可以跳躍的最大長度。 題目保證始從最左邊的格子點出發開始跳,一定可以成功抵達終點,請問最少跳躍次數是說少? 題目的原文敘述 測試範例 Example 1: Input: nums = [2,3,1,1,4] Outp
Thumbnail
題目敘述 題目會給我們一個輸入陣列nums,每個元素值代表那個格子點可以跳躍的最大長度。 題目保證始從最左邊的格子點出發開始跳,一定可以成功抵達終點,請問最少跳躍次數是說少? 題目的原文敘述 測試範例 Example 1: Input: nums = [2,3,1,1,4] Outp
Thumbnail
題目敘述 題目會給定我們一顆二元搜索樹BST的根結點, 還有一個指定區間的上邊界R 和 下邊界L。 請問二元搜索樹中,所有落在指定區間內的節點元素值的總和是多少? 題目的原文敘述 測試範例 Example 1: Input: root = [10,5,15,3,7,null,18], l
Thumbnail
題目敘述 題目會給定我們一顆二元搜索樹BST的根結點, 還有一個指定區間的上邊界R 和 下邊界L。 請問二元搜索樹中,所有落在指定區間內的節點元素值的總和是多少? 題目的原文敘述 測試範例 Example 1: Input: root = [10,5,15,3,7,null,18], l
Thumbnail
題目會給我們一個排序好的陣列,還有一個目標值target 要求我們在陣列中尋找target所在的索引位置。 如果target 不存在,返回-1 題目要求必須在O( log n )對數時間內完成 。
Thumbnail
題目會給我們一個排序好的陣列,還有一個目標值target 要求我們在陣列中尋找target所在的索引位置。 如果target 不存在,返回-1 題目要求必須在O( log n )對數時間內完成 。
Thumbnail
假設有天你要在電話簿找一個K開頭的人,或是O開頭的人 你並不會從A開始找 一定是從最接近的開始找。 二分搜尋是一種演算法 下方是二分搜尋演算法的如何作用 STEP 1 圖一這是一組陣列,由小到大排列,其中我們在這陣列要找的數字是“13”所以我們必須把它存在 searchForNumber 這個變數裡
Thumbnail
假設有天你要在電話簿找一個K開頭的人,或是O開頭的人 你並不會從A開始找 一定是從最接近的開始找。 二分搜尋是一種演算法 下方是二分搜尋演算法的如何作用 STEP 1 圖一這是一組陣列,由小到大排列,其中我們在這陣列要找的數字是“13”所以我們必須把它存在 searchForNumber 這個變數裡
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News