zoukankan      html  css  js  c++  java
  • 532. K-diff Pairs in an Array

    原题链接:https://leetcode.com/problems/k-diff-pairs-in-an-array/description/
    这道题目很有意思哦,但是我始终没有写出实现来,下面是抄袭讨论区的答案啦:

    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * Created by clearbug on 2018/2/26.
     */
    public class Solution {
    
        public static void main(String[] args) {
            Solution s = new Solution();
            System.out.println(s.findPairs(new int[]{1, 3, 1, 5, 4}, 0));
        }
    
        // 自己整了半天没有想出答案,看了讨论区别人的答案啊
        public int findPairs(int[] nums, int k) {
            if (nums == null || nums.length == 0 || k < 0) {
                return 0;
            }
    
            int count = 0;
    
            Map<Integer, Integer> map = new HashMap<>(nums.length);
            for (int item : nums) {
                map.put(item, map.getOrDefault(item, 0) + 1);
            }
    
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                if (k == 0) {
                    if (entry.getValue() >= 2) {
                        count++;
                    }
                } else {
                    if (map.containsKey(entry.getKey() + k)) {
                        count++;
                    }
                }
            }
    
            return count;
        }
    }
    

    明天下午就要去新浪面试了,还有一大堆东西没有复习,晚上一个小时看了几集《银魂》过去了。。。此刻,灰常紧张。。。这道题目就先到这里了,感觉还是有更简单的方法的,毕竟题目的 Related Topics 里面提到了:Two Pointers

  • 相关阅读:
    类与类之间的关系图
    UML介绍
    数据建模
    状态图
    部署图
    用例图
    业务建模
    时序图
    postgresql 维护手册
    ashx文件的使用(转)
  • 原文地址:https://www.cnblogs.com/optor/p/8647375.html
Copyright © 2011-2022 走看看