Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Idea is the same: climbing up the hill along one edge (Greedy)! Visualize it in your mind!

class Solution {
public:
    /**
     * @param A: An integer matrix
     * @return: The index of the peak
     */
    vector<int> findPeakII(vector<vector<int> > A) 
    {
        int n = A.size();
        int m = A[0].size();
        
        int i = 1, j = 1;
        while(i < m - 1 && j < n - 1)
        {
            bool up   = A[j - 1][i] < A[j][i];
            bool down = A[j + 1][i] < A[j][i];
            bool left = A[j][i - 1] < A[j][i];
            bool right= A[j][i + 1] < A[j][i];
            
            if(up && down && left && right)
            {
                return {j, i};
            }
            if(!down && j < n - 2)
            {
                j ++;
            }
            else if(!right && i < m - 2)
            {
                i ++;
            }
        }
        
        return {-1, -1};
    }
};
posted on 2015-10-06 07:45  Tonix  阅读(161)  评论(0编辑  收藏  举报