[LeetCode] 1. Two Sum ☆
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 ☆的更多相关文章
- 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 ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- [leetCode][013] Two Sum 2
题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...
- [LeetCode] #167# Two Sum II : 数组/二分查找/双指针
一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...
- [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针
一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...
- [array] leetcode - 40. Combination Sum II - Medium
leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...
- [array] leetcode - 39. Combination Sum - Medium
leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...
- LeetCode one Two Sum
LeetCode one Two Sum (JAVA) 简介:给定一个数组和目标值,寻找数组中符合求和条件的两个数. 问题详解: 给定一个数据类型为int的数组,一个数据类型为int的目标值targe ...
- [leetcode]40. Combination Sum II组合之和之二
Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...
- [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 ...
随机推荐
- Python3 Tkinter-Frame
1.创建 from tkinter import * root=Tk() for fm in ['red','blue','yellow','green','white','black']: Fram ...
- 基于spring-boot、spring-cloud的websocket服务器多点负载均衡改造
背景 为应对更多用户使用socket的场景,准备对存放websocket的服务器进行多点搭建并配置负载均衡. 问题 服务器上了多点负载均衡以后,基于socket的部分功能发生了有规律的失效,查看后台日 ...
- 浮点数(floating-point number)二进制存储格式
定义 浮点数就是小数点位置不固定的数,也就是说与定点数不一样,浮点数的小数点后的小数位数可以是任意的,根据IEEE754-1985(也叫IEEE Standard for Binary Floatin ...
- 《C++面试知识点》
[动态内存] 1. 由内置指针管理的动态内存(即new和delete管理动态内存),直到被显式释放之前它都是存在的.假设该指针变量被销毁,那该内存将不会自动释放(即所谓的“内存泄漏”). 2. 可以用 ...
- Notes of the scrum meeting before publishing2(12.18)
meeting time:18:30~20:30p.m.,December 18th,2013 meeting place:3号公寓一层 attendees: 顾育豪 ...
- sql 至少含有
查询Score表中至少有5名学生选修的并以3开头的课程的平均分数: select avg(degree),cnofrom scorewhere cno like '3%'group by cnohav ...
- oracle数据库之存储函数和过程
一.引言 ORACLE 提供可以把 PL/SQL 程序存储在数据库中,并可以在任何地方来运行它.这样就叫存储过程或函数.过程和函数统称为 PL/SQL 子程序,他们是被命名的 PL/SQL 块 ...
- lintcode-30-插入区间
插入区间 给出一个 无重叠 的按照区间起始端点排序的区间列表. 在列表中插入一个新的区间,你要确保列表中的区间仍然有序且 不重叠 (如果有必要的话,可以合并区间). 样例 插入区间[2, 5] 到 [ ...
- C#里面Console.Write()和Console.WriteLine()有什么区别?
Console.Write()和Console.WriteLine()都是System.Console提供的方法,两着主要用来将输出流由指定的输出装置(默认为屏幕)显示出来.两着间的差异在Consol ...
- SpringBoot Web(SpringMVC)
入门工程: package com.example.demo.controller; import com.example.demo.entity.User; import org.springfra ...