双指针和滑动窗口的简易使用

132 阅读1分钟

双指针

思路:定义 left 和 right 两个指针,left 指针从数组始端开始搜索,right 指针从数组末端开始搜索,而且一般还需要排序

面试题 16.24. 数对和

class Solution {
    public List<List<Integer>> pairSums(int[] nums, int target) {
        HashMap<Integer, Integer> hash = new HashMap();
        List<List<Integer>> ans = new ArrayList<>();

        int left = 0;
        int right = nums.length - 1;
        Arrays.sort(nums);
        while (left < right) {
            int sum = nums[left] + nums[right];
            if (sum == target) {
                List<Integer> list = new ArrayList<>();
                list.add(nums[left]);
                list.add(nums[right]);
                ans.add(list);
                left++;
                right--;
            } else if(sum > target) {
                right--;
            } else {
                left++;
            }
        }
        return ans;
    }
}

滑动窗口

思路:定义front和behind两个指针,从数组始端不断根据已知条件移动两个指针,获取两个指针区间内的长度或值

643. 子数组最大平均数 I

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
       int sum = 0;
        int maxn = -1000000001;
        int l = 0, r = -1;
        int n = nums.size();
        while(r < n - 1) { // 注意r的停止条件
            r++;
            sum += nums[r];
            while (r - l + 1 > k) {
                sum -= nums[l];
                l++;
            }
            
            if(r - l + 1 == k) {
                maxn = max(maxn, sum);
            }
        }
        return maxn * 1.0 / k;
    }
};