2019拼多多提前批筆試題(算法崗)

一共四道編程題:

第一題 :給一個數組,求最長的山谷。

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

最長的山谷是 5 3 2 3 4,長度是5.

本題類似於lettcode 845,求最長山峯。

trick:筆試的輸入很坑,沒有給定輸入長度,導致輸入處理很麻煩,導致程序出錯。

求山峯的代碼:

class Solution {
    public int longestMountain(int[] A) {
        int cnt = 0;
        int l, r;
        for(int i = 1; i < A.length-1; i++){
            if(A[i-1] < A[i] && A[i] > A[i+1]){
                l = i-1;
                r = i+1;
                while(l >= 1 && A[l]>A[l-1]) l--;
                while(r < A.length-1 && A[r]>A[r+1]) r++;
                cnt = Math.max(cnt, r-l+1);
            }
        }
        return cnt;
    }
}

第二、三、四題見下一篇博客。

https://blog.csdn.net/aoxue_bai/article/details/81179740

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章