码迷,mamicode.com
首页 > 其他好文 > 详细

3 - Two Pointers Algorithm

时间:2019-04-21 09:21:59      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:from   font   另一个   tps   bsp   替换   write   OLE   number   

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

标签:from   font   另一个   tps   bsp   替换   write   OLE   number   

原文地址:https://www.cnblogs.com/jenna/p/10743830.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!