LeetCode 5题 --Array+Binary search

这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;
    }
};
时间: 2024-10-09 01:26:59

LeetCode 5题 --Array+Binary search的相关文章

【leetcode刷题笔记】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 duplic

【leetcode刷题笔记】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. 题解:如果没有重复的元素,那么就可以根据target是否在某一半而扔掉另外一半.但是如果有

LeetCode 33 Search in Rotated Sorted Array [binary search] &lt;c++&gt;

LeetCode 33 Search in Rotated Sorted Array [binary search] <c++> 给出排序好的一维无重复元素的数组,随机取一个位置断开,把前半部分接到后半部分后面,得到一个新数组,在新数组中查找给定数的下标,如果没有,返回-1.时间复杂度限制\(O(log_2n)\) C++ 我的想法是先找到数组中最大值的位置.然后以此位置将数组一分为二,然后在左右两部分分别寻找target. 二分寻找最大值的时候,因为左半部分的数一定大于nums[l],所以n

leetcode第一刷_Unique Binary Search Trees

这道题其实跟二叉搜索树没有什么关系,给定n个节点,让你求有多少棵二叉树也是完全一样的做法.思想是什么呢,给定一个节点数x,求f(x),f(x)跟什么有关系呢,当然是跟他的左右子树都有关系,所以可以利用其左右子树的结论,大问题被成功转化成了小问题.最熟悉的方法是递归和dp,这里显然有大量的重复计算,用dp打表好一些. 后来实验的同学说,这其实是一个Catalan数,上网查了一下,果然啊.Catalan数是这样子的: h(0) = 1, h(1) = 1; 递推式:h(n)= h(0)*h(n-1)

leetcode第一刷_Recover Binary Search Tree

这是一道好题,思路虽然有,但是提交之后总是有数据过不了,又按照数据改改改,最后代码都没法看了.收到的教训是如果必须为自己的代码加上很多很多特殊的限定,来过一些特殊的数据的话,说明代码本身有很大的漏洞. 这道题,我想到了要用两个指针保存乱序的节点,甚至想到了用一个pre指针来保存前面一个节点,但是问题出在哪里呢?我觉得应该是自己对树的遍历理解的不够深刻.既然知道了二叉搜索树一定是用中序遍历的,那么程序的框架应该马上写的出来,先左子树,再根,再右子树,那你说什么时候更新pre指针呢,当然是访问根节点

LeetCode详细分析 :: Recover Binary Search Tree [Tree]

Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 这里

【一天一道LeetCode】#96. Unique Binary Search Trees

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given n, how many structurally unique BST's (binary search trees) that store values 1-n? For example, Given n = 3, there are a total of 5 unique BST's. (二)解题

【leetcode刷题笔记】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 ro

leetcode第一刷_Unique Binary Search Trees II

http://acm.hdu.edu.cn/showproblem.php?pid=1507 大致题意:在一个n*m的格子上,黑色的地方不可用,问在白色格子上最多可放多少1*2的矩阵. 思路:建图,每个白色格子与它临近的上下左右的白色格子建边,求最大匹配,答案为最大匹配/2,因为是双向图.最后输出匹配边时,当找到一组匹配边记得将该边标记,以防重复计算. #include <stdio.h> #include <algorithm> #include <set> #inc