美文网首页
leetcode349,350,1查找表

leetcode349,350,1查找表

作者: __hgb | 来源:发表于2019-06-07 11:18 被阅读0次
    349.png
        public int[] intersection(int[] nums1, int[] nums2) {
    
            HashSet<Integer> record = new HashSet<Integer>();
            for(int num: nums1)
                record.add(num);
    
            HashSet<Integer> resultSet = new HashSet<Integer>();
            for(int num: nums2)
                if(record.contains(num))
                    resultSet.add(num);
    
            int[] res = new int[resultSet.size()];
            int index = 0;
            for(Integer num: resultSet)
                res[index++] = num;
    
            return res;
        }
    
    350.png
        public int[] intersect(int[] nums1, int[] nums2) {
            HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
            for(int num: nums1)
                if(!record.containsKey(num))
                    record.put(num, 1);
                else
                    record.put(num, record.get(num) + 1);
    
            ArrayList<Integer> result = new ArrayList<Integer>();
            for(int num: nums2)
                if(record.containsKey(num) && record.get(num) > 0){
                    result.add(num);
                    record.put(num, record.get(num) - 1);
                }
    
            int[] ret = new int[result.size()];
            int index = 0;
            for(Integer num: result)
                ret[index++] = num;
            return ret;
        }
    
    1.png
     public int[] twoSum(int[] nums, int target) {
    
            HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
            for(int i = 0 ; i < nums.length; i ++){
    
                int complement = target - nums[i];
                if(record.containsKey(complement)){
                    int[] res = {i, record.get(complement)};
                    return res;
                }
    
                record.put(nums[i], i);
            }
    
            throw new IllegalStateException("the input has no solution");
        }
    

    相关文章

      网友评论

          本文标题:leetcode349,350,1查找表

          本文链接:https://www.haomeiwen.com/subject/rijmxctx.html