Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解法1:最直接最笨的办法,遍历数组中的每一个数,从它之后的数中寻找是否有满足条件的,找到后跳出循环并返回。由于需要两次遍历,时间复杂度为O(n2),空间复杂度为O(1)。

public class Solution {
public int[] twoSum(int[] nums, int target) {int result[] = new int[]{-1, -1};
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j ++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
break;
}
}
if ((result[0] != -1) && (result[1] != -1)) {
break;
}
}
return result;
}
}

解法2-1: 先遍历一遍数组,将每个数字存到hash表中,然后再遍历一遍,查找符合要求的数。由于存储和遍历的操作时间复杂度都是O(n),所以总体时间复杂度为O(n),而空间复杂度为O(n)。

public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> numHash = new HashMap<>();
int result[] = new int[2];
for (int i = 0; i < nums.length; i++) {
numHash.put(nums[i], i);
} for (int i = 0; i < nums.length; i++) {
int other = target - nums[i];
if (numHash.containsKey(other) && numHash.get(other) != i) {
result[0] = i;
result[1] = numHash.get(other);
break;
}
}
return result;
}
}

解法2-2:将2-1的两次循环合并,每次先判断hashmap中是否有满足条件的数,没有的话再将当前数写入hashmap中,进行下一次循环。

public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> numHash = new HashMap<>();
int result[] = new int[2];
for (int i = 0; i < nums.length; i++) {
int other = target - nums[i];
if (numHash.containsKey(other)) {
result[0] = i;
result[1] = numHash.get(other);
break;
}
numHash.put(nums[i], i);
}
return result;
}
}

解法3: 先将数组拷贝(O(n))后采用Arrays.sort()方法进行排序,排序的时间复杂度为O(nlogn)。然后采用二分搜索法查找(O(n)),最后将找出的结果在原数组中查找其下标(O(n)),所以整体时间复杂度为(O(nlogn))。

public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2]; int[] copyList = new int[nums.length];
System.arraycopy(nums, 0, copyList, 0, nums.length);
Arrays.sort(copyList); int low = 0;
int high = copyList.length - 1;
while(low < high) {
if (copyList[low] + copyList[high] < target) {
low++;
} else if (copyList[low] + copyList[high] > target) {
high--;
} else {
result[0] = copyList[low];
result[1] = copyList[high];
break;
}
} int index1 = -1;
int index2 = -1;
for (int i = 0; i < nums.length; i++) {
if ((index1 == -1) && (nums[i] == result[0])) {
index1 = i;
} else if ((index2 == -1) && (nums[i] == result[1])) {
index2 = i;
}
}
result[0] = index1;
result[1] = index2;
Arrays.sort(result);
return result;
}
}

[LeetCode] 1. Two Sum ☆的更多相关文章

  1. Java for LeetCode 216 Combination Sum III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  2. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  3. [leetCode][013] Two Sum 2

    题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...

  4. [LeetCode] #167# Two Sum II : 数组/二分查找/双指针

    一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...

  5. [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针

    一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...

  6. [array] leetcode - 40. Combination Sum II - Medium

    leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...

  7. [array] leetcode - 39. Combination Sum - Medium

    leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...

  8. LeetCode one Two Sum

    LeetCode one Two Sum (JAVA) 简介:给定一个数组和目标值,寻找数组中符合求和条件的两个数. 问题详解: 给定一个数据类型为int的数组,一个数据类型为int的目标值targe ...

  9. [leetcode]40. Combination Sum II组合之和之二

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

  10. [LeetCode] 437. Path Sum III_ Easy tag: DFS

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

随机推荐

  1. leetcode个人题解——#18 4sums

    在3sums的基础上加了一层循环. class Solution { public: vector<vector<int>> fourSum(vector<int> ...

  2. java报错:Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE

    Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE at org.apache.http.conn.ss ...

  3. ArrayList遍历(JAVA)

    假如有个ArrayList变量如下: ArrayList<String> list = new ArrayList<String>(); list.add("arra ...

  4. asp.net中Repeater结合js实现checkbox的全选/全不选

    前台界面代码: <input name="CheckAll" type="checkbox" id="CheckAll" value= ...

  5. js控制input只能输入数字和小数点后两位,输入其他自动清除方法。

    工作中input='text'总会遇到要控制输入数字,或者是输入中文,输入电话,输入身份证号,邮箱等.今天我遇到的是要输入数字并且只能小数点后面两位的数字,还不能为负数.废话不多说上代码: <i ...

  6. lol人物模型提取(二)

      两个dds文件怎么导入到一个模型上呢?这模型又不能拆开.   一开始我想的是用两个材质球来完成,一个材质球对应一个dds文件,然而行不通.   一个材质球对应两个dds文件还不太会弄,于是我想着干 ...

  7. mysql+navicat安装小结

    1,mysql到官方下载,navicat下载破解版 2,修改my.ini, 注意,需要手动创建data文件夹, 其中C:\MySql\mysql-5.7.17-winx64是解压mysql的目录 [m ...

  8. JAVA学习之泛型

    ArrayList<E>类定义和ArrayList<Integer>类引用中涉及的术语:1.整个ArrayList<E>称为泛型类型 2.ArrayList< ...

  9. Maven jeetsite项目 搭建

    , 一直没有系统的总结一下Maven的知识,今天,想从网上找一个Maven的项目,练练手,顺便学习一下maven的原理 和布局. 官网:http://www.jeesite.com/ 没想到,上来就给 ...

  10. 使用js 复制 文字到剪贴板

    有一个好插件 https://clipboardjs.com/ 兼容性  IE9+ 一般基本够用,但如果非要兼容IE8 可使用IE 特有的 方法 window.clipboardData.setDat ...