3 - Two Pointers Algorithm

Posted jenna

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3 - Two Pointers Algorithm相关的知识,希望对你有一定的参考价值。

607. Two Sum III - Data structure design (查找问题:从 map 中查找一个元素)

双指针:用一个指针遍历 map 所有元素,用另一个指针在 map 中找 remain

https://www.lintcode.com/problem/two-sum-iii-data-structure-design/description?_from=ladder&&fromId=1

1、为什么要使用构造方法初始化 map 呢?

  The TwoSum object will be instantiated and called as such:

  TwoSum twoSum = new TwoSum();

  twoSum.add(number);

  twoSum.find(value);

2.、双指针,最暴力的解法是内外两层 for 循环。优化解法:仅一层循环,从 map 中查找 remain。

public class TwoSum {
    /**
     * @param number: An integer
     * @return: nothing
     */
    Map<Integer, Integer> map = null; //new HashMap<>();
    public TwoSum() {
        map = new HashMap<>();
    }
    public void add(int number) {
        // write your code here
        if(!map.containsKey(number)) {
            map.put(number, 1);
        } else {
            map.put(number, map.get(number) + 1);
        }
    }

    /**
     * @param value: An integer
     * @return: Find if there exists any pair of numbers which sum is equal to the value.
     */
    public boolean find(int value) {
        // write your code here
        for(int num: map.keySet()) {
            int remain = value - num;
            if(num == remain) {
                if(map.containsKey(num) && map.get(num) >= 2) {
                    return true;
                } else {
                    return false;
                }
            } else {
                if(map.containsKey(remain)) {
                    return true;
                }
            }
        }
        return false;
    }
}

 

539. Move Zeroes (替换问题)

https://www.lintcode.com/problem/move-zeroes/description?_from=ladder&&fromId=1

双指针,left 代表新数组,right 代表老数组。

public class Solution {
    /**
     * @param nums: an integer array
     * @return: nothing
     */
    public void moveZeroes(int[] nums) {
        // write your code here
        int len = nums.length;
        int left = 0, right = 0;
        while(right < len) {
            if(nums[right] != 0) {
                int temp = nums[right];
                nums[right] = nums[left];
                nums[left] = temp;
                left++;
            }
            right++;
        }
    }
}

 

以上是关于3 - Two Pointers Algorithm的主要内容,如果未能解决你的问题,请参考以下文章

3 - Two Pointers Algorithm

3 - Two Pointers Algorithm

3 - Two Pointers Algorithm

3 - Two Pointers Algorithm

sorting, two pointers(cf div.3 1113)

[LeetCode-Java] Two Pointers (1-300)