劍指offer-20200319

20200319

題目 :字符串的左旋操作是把字符串前面的若干個字符轉移到字符串的尾部。請定義一個函數實現字符串左旋轉操作的功能。比如,輸入字符串"abcdefg"和數字2,該函數將返回左旋轉兩位得到的結果"cdefgab"。

輸入: s = "abcdefg", k = 2
輸出: "cdefgab"

code

class Solution{
    public String reverseLeftWords(String s, int n){
        return s.substring(n) + s.substring(0,n);
    }
}

題目:滑動窗口的最大值

給定一個數組nums和滑動窗口的大小k,請找出所有滑動窗口裏的最大值。

輸入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
輸出: [3,3,5,5,6,7] 
解釋: 

  滑動窗口的位置                最大值
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

code

class Solution{
    public int[] maxSlidingWindow(int[] nums,int x){
        if(nums == null || nums.length == 0){
            return new int[0];
        }
        int[] res = new int[nums.length-k+1];
        Deque<Integer> queue = new ArrayDeque<>();
        for(int i=0,j=0;i < nums.length;i++){
            if(!queue.isEmpty() && i - queue.peek() >= k){
                queue.poll();
            }
            while(!queue.isEmpty() && nums[i] > nums[queue.peekLast()]){
                queue.pollLast();
            }
            queue.offer(i);
            if(i >= k - 1){
                res[j++] = nums[queue.peek];
            }
            
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章