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. 贵州省未来二十年的投资机会的探讨1>

    贵州的股市 1.000540.SZ 中天金融 2.000589.SZ 黔轮胎A 3.000733.SZ 振华科技 4.000851.SZ 高鸿股份 5.000920.SZ 南方汇通 6.002025. ...

  2. Python3 Tkinter-Listbox

    1.创建 from tkinter import * root=Tk() lb=Listbox(root) for item in ['python','tkinter','widget']: lb. ...

  3. ThinkPHP - 3 - IDE选择以及Eclipse PDT打开ThinkPHP项目

    ThinkPHP框架已部署到SAE(新浪云),且代码已获取到本地.眼前面临的问题就是,对ThinkPHP项目选择哪种开发工具(IDE)? 经过简单的查找比较,以及电脑里已装有Eclipse的因素,遂决 ...

  4. HDU 1250 Hat's Fibonacci(高精度)

    Problem Description A Fibonacci sequence is calculated by adding the previous two members the sequen ...

  5. 【转】Expressions versus statements in JavaScript

    原文地址:http://www.2ality.com/2012/09/expressions-vs-statements.html Update 2012-09-21: New in Sect. 4: ...

  6. c++远征

    ---恢复内容开始--- 这两天初步接触了C++,抱着一种对这两个加号的理解的心态走进这门语言的学习. 1.mooc--慕课网c++课程链接:http://www.imooc.com/learn/34 ...

  7. 向redis插入数据时,返回值问题

    向redis插入数据时,如果redis没有要插入的key,插入成功之后返回值为1 如果redis有这个key,插入成功之后返回值是0

  8. python学习第一天-语法学习

    1.python简介 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,Guido开始写能够解释Python语言语法的解释器.Python这个名字,来自 ...

  9. 201621123033 《Java程序设计》第5周学习总结

    1. 本周学习总结 1.1 写出你认为本周学习中比较重要的知识点关键词 接口 Comparable Comparator 1.2 尝试使用思维导图将这些关键词组织起来.注:思维导图一般不需要出现过多的 ...

  10. "亿家App"问卷调查分析结果及心得体会

    一.问卷问题设计 调查背景:随着现代社会互联网的发展,基于家庭产生的服务项目也越来越多.为增加家庭之间的交流和互助,增加家庭内部.家庭与家庭之间的沟通互助,并利用互联网便捷交流的优势,使家庭在享受服务 ...