zoukankan      html  css  js  c++  java
  • 54. Search a 2D Matrix && Climbing Stairs (Easy)

     

     

     

     

     

    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.

    思路: 从右上方开始,若小于 target, 则往下走;若大于 target, 对改行二分查找;若等 target, 返回 true.

    bool binarySearch(vector<int> &A, int target) {
        int l = 0, h = A.size()-2;
        while(l <= h) {
            int mid = (l+h) >> 1;
            if(A[mid] > target) h = mid-1;
            else if(A[mid] < target) l = mid+1;
            else return true;
        }
        return false;
    }
    class Solution {
    public:
        bool searchMatrix(vector<vector<int> > &matrix, int target) {
            if(!matrix.size() || !matrix[0].size()) return false;
            int row = matrix.size(), col = matrix[0].size();
            for(int r = 0; r < row; ++r) {
                if(matrix[r][col-1] == target) return true;
                if(matrix[r][col-1] > target) return binarySearch(matrix[r], target);
            }
            return false;
        }
    };
    

    Climbing Stairs

    You are climbing a stair case. It takes n steps to reach to the top.

    Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

    思路:  斐波那契。此处用动归。 还可以使用矩阵二分乘。(剑指offer: 题9)

    // Fibonacci
    class Solution {
    public:
        int climbStairs(int n) {
            vector<int> f(n+1, 0);
            f[0] = f[1] = 1;
            for(int i = 2; i <= n; ++i) f[i] = f[i-1] + f[i-2];
            return f[n];
        }
    };
    
  • 相关阅读:
    2019 SDN上机第5次作业
    hdu 2553 N皇后问题(递归)
    百练oj 2766 最大子矩阵和
    POJ 1664 放苹果
    POJ 3617 Best Cow Line(贪心)
    HDU 2013 ACM/ICPC Asia Regional Hangzhou Online ------ Zhuge Liang's Mines
    HDU 4712 Hamming Distance (随机算法)
    HDU 1171 Big Event in HDU
    HDU 1085 Holding Bin-Laden Captive!
    HDU 1028 母函数
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3954305.html
Copyright © 2011-2022 走看看