LeetCode 5題 --Array+Binary search

來源:互聯網
上載者:User

標籤:binary search   leetcode   array   

這5道題都是array的binary search就可以搞定了

分別是leetcode(35)——Search Insert Position  leetcode(33)——Search in Rotated Sorted Array  leetcode(81)——Search in Rotated Sorted Array II  leetcode(34)——Search for a Range  leetcode(74)——Search a 2D Matrix

一:leetcode(35)——Search Insert Position

題目:

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

連結:https://leetcode.com/problems/search-insert-position/

分析:通過分析我們發現當找到直接返回mid就可以了,當沒找到需要返回begin就滿足要求了

class Solution {public:    int searchInsert(int A[], int n, int target) {        int begin = 0, end = n-1;        int mid = 0;        while(begin <= end){    // 二分尋找+判斷邊界            mid = (begin+end)/2;            if(A[mid] == target) return mid;            else if(A[mid] < target) begin = mid+1;            else end = mid-1;        }        return begin;            }};

二:leetcode(33)——Search in Rotated Sorted Array

題目:

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

連結:https://leetcode.com/problems/search-in-rotated-sorted-array/

分析:只要我們找到最小值O(N)時間,然後通過最後一個元素確定二分尋找的區間就可以了

class Solution {public:    int search(int A[], int n, int target) {        if(n == 0) return -1;        int minNum = A[0];        int index = 0;        for(int i = 1; i < n; i++){  // 找到最小元素            if(A[i] < minNum){                minNum = A[i];                index = i;            }        }        int begin = 0, end = n-1;      // 看在哪個區間         if(A[n-1] >= target)         // 注意這裡是大於等於            begin = index;        else            end = index-1;                    while(begin <= end){            int mid = (begin+end)/2;            if(A[mid] == target) return mid;            else if(A[mid] < target) begin = mid+1;            else end = mid-1;        }        return -1;            }};
三:leetcode(81)——Search in Rotated Sorted Array II

題目:

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.


連結:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/

分析:這裡要求元素可以重複,因此我們需要找到緊靠最大值的最小即可,其它思路和上題一模一樣

class Solution {public:    bool search(int A[], int n, int target) {        if(n == 0) return false;        int minNum = A[0];        int index = 0;        for(int i = 1; i < n; i++){  // 找到最小元素            if(A[i] <= minNum && A[i-1] > A[i]){         // 只改變了一點 確保最大值最小值相鄰                minNum = A[i];                index = i;            }        }        int begin = 0, end = n-1;      // 通過A[n-1]看在哪個區間         if(A[n-1] >= target)         // 注意這裡是大於等於            begin = index;        else            end = index-1;                    while(begin <= end){            int mid = (begin+end)/2;            if(A[mid] == target) return true;            else if(A[mid] < target) begin = mid+1;            else end = mid-1;        }        return false;    }};

四: leetcode(34)——Search for a Range

題目:

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm‘s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

連結:https://leetcode.com/problems/search-for-a-range/

分析:當通過二分尋找找到該元素時,我們並沒有直接返回,而是通過判斷begin和end處是否等於target,如果不等則通過begin++ 與end--逐漸逼近

class Solution {public:    vector<int> searchRange(int A[], int n, int target) {        int begin = 0, end = n-1;        vector<int> result(2, -1);        while(begin <= end){            int mid = (begin+end)>>1;            if( A[mid]== target){                if(A[begin] == target && A[end] == target){  // 當中間值相等時直到左右區間都等於target才終止                    result[0]= begin;                        result[1] = end;                    break;                }                 if(A[begin] != target) begin++;        // 否則begin++ end--逐漸逼近                if(A[end] != target) end--;                            }else if(A[mid] < target) begin = mid+1;            else end = mid-1;        }        return result;    }};

五:leetcode(74)——Search a 2D Matrix

題目:

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[  [1,   3,  5,  7],  [10, 11, 16, 20],  [23, 30, 34, 50]]

Given target = 3, return true.

連結:https://leetcode.com/problems/search-a-2d-matrix/

分析:此題通過兩次二分尋找,先確定元素所在的行,然後在行中進行二分尋找即可。

class Solution {public:    bool searchMatrix(vector<vector<int> > &matrix, int target) {        int m = matrix.size();        if(m == 0) return false;        int n = matrix[0].size();        int begin = 0, end = m-1;        int mid = 0;        while(begin <= end){                // 先對第一列進行二分尋找找到元素所在行            mid = (begin+end)/2;            if(matrix[mid][0] == target) return true;            else if(matrix[mid][0] < target) begin = mid+1;            else end = mid-1;        }                int currentRow = 0;        if(matrix[mid][0] > target) currentRow = mid -1;        else currentRow = mid;        if(currentRow < 0) return false;                 begin = 0, end = n-1;         while(begin <= end){           // 然後對找到的行進行二分尋找            mid = (begin + end)/2;            if(matrix[currentRow][mid] == target) return true;            else if(matrix[currentRow][mid] < target)begin = mid+1;            else end = mid-1;        }        return false;    }};




LeetCode 5題 --Array+Binary search

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.