zoukankan      html  css  js  c++  java
  • 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++;
            }
        }
    }
  • 相关阅读:
    SA(后缀数组)专题总结
    LCT总结
    多项式全家桶
    fft.ntt,生成函数,各种数和各种反演
    P3939 数颜色
    P1879 [USACO06NOV]玉米田Corn Fields
    主席树模板
    P2633 Count on a tree
    P1972 [SDOI2009]HH的项链
    数论
  • 原文地址:https://www.cnblogs.com/jenna/p/10743830.html
Copyright © 2011-2022 走看看