1). two-sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

思路一: 暴力搜索,时间复杂度O(n*n);

思路二:Map

public class Solution{
public int[] twoSum(int[] numbers,int target){
int len=numbers.length;
int[] index=new int[2]; HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<numbers.length;i++){
if(!map.containsKey(numbers[i]){
map.put(target-numbers[i],i);
}else{
index[0]=map.get(numbers[i]);
index[1]=i;
}
}
return index;
}
}

2). 3sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)

思路一:三重循环,时间复杂度是O(n^3),而且还要处理重复的问题;

思路二:

  先升序排序,然后用第一重for循环确定第一个数字。然后在第二重循环里,第二、第三个数字分别从两端往中间扫。如果三个数的sum等于0,得到一组解。如果三个数的sum小于0,说明需要增大,所以第二个数往右移。如果三个数的sum大于0,说明需要减小,所以第三个数往左移。时间复杂度:O(n2)

注意:

  1、排序之后天然满足non-descending order的要求

  2、为了避免重复,在没有空间要求情况下可以用map,但是也可以跳过重复元素来做。

public class Solution {  

    public List<List<Integer>> threeSum(int[] num) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
int len = num.length, tar = 0; if (len <= 2)
return ret; Arrays.sort(num); for (int i = 0; i <= len - 3; i++) {
// first number : num[i]
int j = i + 1; // second number
int k = len - 1; // third number
while (j < k) {
if (num[i] + num[j] + num[k] < tar) {
++j;
} else if (num[i] + num[j] + num[k] > tar) {
--k;
} else {
ret.add(Arrays.asList(num[i], num[j], num[k]));
++j;
--k;
// folowing 3 while can avoid the duplications
while (j < k && num[j] == num[j - 1])
++j;
while (j < k && num[k] == num[k + 1])
--k;
}
}
while (i <= len - 3 && num[i] == num[i + 1])
++i;
}
return ret; }
}

3).4sum

Given an array S of n integers, are there elements abc, and d in S such that a + bc + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.
    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)

思路一:跟之前的 2Sum, 3Sum 一样的做法,先排序,再左右夹逼

思路二: 先求出每两个数的和,放到 HashSet 里,再利用之前的 2Sum 去求。这种算法比较快,复杂度 O(nnlog(n)),不过细节要处理的不少。

public class Solution {
public List<List<Integer>> fourSum(int[] num, int target) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
HashMap<Integer, List<Integer[]>> hm = new HashMap<Integer, List<Integer[]>>();
int len = num.length; Arrays.sort(num);
// store pair
for (int i = 0; i < len - 1; ++i) {
for (int j = i + 1; j < len; ++j) {
int sum = num[i] + num[j];
Integer[] tuple = {num[i], i, num[j], j};
if (!hm.containsKey(sum)) {
hm.put(sum, new ArrayList<Integer[]>());
}
hm.get(sum).add(tuple);
}
} Integer[] keys = hm.keySet().toArray(new Integer[hm.size()]);
for (int key : keys) {
if (hm.containsKey(key)) {
if (hm.containsKey(target - key)) {
List<Integer[]> first_pairs = hm.get(key);
List<Integer[]> second_pairs = hm.get(target - key); for (int i = 0; i < first_pairs.size(); ++i) {
Integer[] first = first_pairs.get(i);
for (int j = 0; j < second_pairs.size(); ++j) {
Integer[] second = second_pairs.get(j);
// check
if (first[1] != second[1] && first[1] != second[3] &&
first[3] != second[1] && first[3] != second[3]) {
List<Integer> ans = Arrays.asList(first[0], first[2], second[0], second[2]);
Collections.sort(ans);
if (!ret.contains(ans)) {
ret.add(ans);
}
}
}
} hm.remove(key);
hm.remove(target - key);
}
}
} return ret;
}
}
 

leetcode: 哈希——two-sum,3sum,4sum的更多相关文章

  1. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

  2. LeetCode Two Sum&Two Sum II - Input array is sorted&3Sum&4Sum 一锅煮题解

    文章目录 Two Sum Two Sum II 3Sum 4Sum Two Sum 题意 给定一个数组,和指定一个目标和.从数组中选择两个数满足和为目标和.保证有且只有一个解.每个元素只可以用一次. ...

  3. LeetCode 2 Add Two Sum 解题报告

    LeetCode 2 Add Two Sum 解题报告 LeetCode第二题 Add Two Sum 首先我们看题目要求: You are given two linked lists repres ...

  4. leetcode 练习1 two sum

    leetcode 练习1  two sum whowhoha@outlook.com 问题描述 Given an array of integers, return indices of the tw ...

  5. [LeetCode] Minimum Size Subarray Sum 解题思路

    Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...

  6. 【一天一道LeetCode】#113. Path Sum II

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  7. 【一天一道LeetCode】#40. Combination Sum II

    一天一道LeetCode系列 (一)题目 Given a collection of candidate numbers (C) and a target number (T), find all u ...

  8. 乘风破浪:LeetCode真题_040_Combination Sum II

    乘风破浪:LeetCode真题_040_Combination Sum II 一.前言 这次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素即可. 二.Combination Sum ...

  9. 乘风破浪:LeetCode真题_039_Combination Sum

    乘风破浪:LeetCode真题_039_Combination Sum 一.前言     这一道题又是集合上面的问题,可以重复使用数字,来求得几个数之和等于目标. 二.Combination Sum ...

  10. 【LeetCode】813. Largest Sum of Averages 解题报告(Python)

    [LeetCode]813. Largest Sum of Averages 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博 ...

随机推荐

  1. 数据分析之Anaconda安装

    Anaconda概述 Anaconda是一个用于科学计算的Python发行版,支持 Linux, Mac, Windows系统,提供了包管理与环境管理的功能,可以很方便地解决多版本python并存.切 ...

  2. github访问慢解决

    参考:https://github.com/chenxuhua/issues-blog/issues/3 hosts文件: # GitHub Start 192.30.253.112 github.c ...

  3. js网页瀑布流布局

    瀑布流布局思路: 1.css样式,图片的父级div样式设置为定位或者浮动 2.找出图片父级元素(box)和最外元素(main):获取box的宽度和main的宽,然后计算main容器一行能容纳多少个bo ...

  4. 第一章javascript简介

    javascript 当诞生于1995 最开始是目的是处理在服务器端进行的表单验证:让其在服务器端验证改为在服务端验证,大大提高速度(当时网络慢) 如今javascript是一门功能全面的语言,包含闭 ...

  5. Message Unable to connect to SQL Server '(local)'

    最近在sql server 加了一些job,但是run job的时候发生了一下错误: ssage Unable to connect to SQL Server '(local)' 问题根源:调用 T ...

  6. SpringMVC中的视图和视图解析器

    对于控制器的目标方法,无论其返回值是String.View.ModelMap或是ModelAndView,SpringMVC都会在内部将它们封装为一个ModelAndView对象进行返回.  Spri ...

  7. Android Studio 2.2以上支持了Cmake的配置JNI的相关参数

    Android Studio 2.2以上支持了Cmake的配置JNI的相关参数,简化了通过Android.mk配置.并很好的继承了C++的编辑方式.以下是对应的引入第三方so和第三方.cpp文件的路径 ...

  8. git使用笔记-比较分支差异

    比如我们有 2 个分支:master, dev,现在想查看这两个 branch 的区别,有以下几种方式: 1.查看 dev 有,而 master 中没有的: git log dev ^master 同 ...

  9. Spring Cloud学习笔记之微服务架构

    目录 什么是微服务 架构优点 架构的挑战 设计原则 什么是微服务     微服务构架方法是以开发一种小型服务的方式,来开发一个独立的应用系统的.     其中每个小型服务都运行在自己的进程中,并经常采 ...

  10. 《深入浅出Node.js》学习笔记(一)

    看了朴灵前辈的node.js系列文章,很开阔视野,虽然能力有限还是有很多不懂,但是还是希望能写下笔记,初步对node.js有点了解. 一.概念 Node.js不是JS应用.而是JS运行平台 Node. ...