剑指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;
    }
}
发布了94 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_31900497/article/details/104956247