LeetCode--Array--Two sum (Easy)
1.Two sum (Easy)#
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].
solution##
题意是给定一个int数组nums和一个整数target,在nums里面找到两数之和为target的数,并返回两数的数组索引。假定nums数组里面只有唯一的一组结果,且同一个数字只能使用一次。
1.最容易想到的暴力算法,也就是我起初想到的!!!
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
for (int i = 0; i < nums.length - 1; i++)
{
for (int j = i + 1; j < nums.length; j++)
{
if (nums[i] + nums[j] == target)
{
indices[0] = i;
indices[1] = j;
return indices;
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
2.速度更快的解法,HashMap
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> m = new HashMap<Integer,Integer>();
for (int i = 0; i < nums.length; i++)
{
int complement = target - nums[i];
if (m.containsKey(complement))
return new int[] {m.get(complement),i};
m.put(nums[i],i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
reference
https://leetcode.com/articles/two-sum/
总结##
第一种暴力算法就是先取一个数,然后用这个数依次与后面的每一个数相加求和,若和与target相等,则将这两个数的数组索引加入到一个新的int数组中,然后返回这个int数组。time complexity:O(n^2),space complexity:O(1)
第二种使用HashMap的方法起初不太容易想到。基本思路是将数组值作为键,索引作为值。是先创建一个hashmap,然后遍历数组nums,如果hashmap中已经存在complement=target-nums[i]这个元素,则将complement键对应的值(即数组索引),和i存到一个新的int数组里面并返回;若果不存在,则将nums[i],i分别作为键与值存到hashmap中去。如果遍历完数组没有找到相应的结果,则抛出异常。time complexity:O(n),space complexity:O(n)
Notes
1.数组值和下标互换是一种常用的技巧,不过只对整数有用;
LeetCode--Array--Two sum (Easy)的更多相关文章
- 【leetcode】Two Sum (easy)
Given an array of integers, find two numbers such that they add up to a specific target number. The ...
- [leetcode] #112 Path Sum (easy)
原题链接 题意: 给定一个值,求出从树顶到某个叶(没有子节点)有没有一条路径等于该值. 思路: DFS Runtime: 4 ms, faster than 100.00% of C++ class ...
- [array] leetcode - 53. Maximum Subarray - Easy
leetcode - 53. Maximum Subarray - Easy descrition Find the contiguous subarray within an array (cont ...
- Leetcode: Split Array Largest Sum
Given an array which consists of non-negative integers and an integer m, you can split the array int ...
- [LeetCode] 167. Two Sum II - Input array is sorted 两数和 II - 输入是有序的数组
Given an array of integers that is already sorted in ascending order, find two numbers such that the ...
- [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] 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 ...
- [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针
一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...
随机推荐
- 怎么搭建python环境?很简单,就几步的事
现在学习python的人越来越多了,而学习python必备的就是搭建python环境,那么,到底怎么搭建python环境呢? 首先,你需要有安装包,这个去官网下载就可以了,如果不会的话,可以看文章底部 ...
- 技术债务(Technical debt)的产生原因及衡量解决
第一次发布代码,就好比借了一笔钱.只要通过不断重写来偿还债务,小额负债可以加速开发.但久未偿还债务会引发危险.复用马马虎虎的代码,类似于负债的利息.整个部门有可能因为松散的实现,不完全的面向对象的设计 ...
- GeoGebra重复手段实现
1.自定义工具部分可以在网上搜一些别人做的工具,主要是把自己经常做的一些任务做成工具,减少重复过程 2.列表部分的简单操作如图所示,实现对三个点的多项式拟合 3.通过序列指令格式可以做一个好玩的效果, ...
- 【selenium】各种exception
selenium中的Exception解释 exception selenium.common.exceptions.ElementClickInterceptedException(msg=None ...
- B - Red and Black 直接BFS+队列
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A ...
- 浏览器中 JS 的事件循环机制
目录 事件循环机制 宏任务与微任务 实例分析 参考 1.事件循环机制 浏览器执行JS代码大致可以分为三个步骤,而这三个步骤的往复构成了JS的事件循环机制(如图). 第一步:主线程(JS引擎线程)中执行 ...
- [PHP][linux] 命令行脚本接收传入参数的
第一种 :用{ $argv }接受参数 第二种 : getopt() 第三种:
- tensorflow1.0 构建lstm做图片分类
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #this is data mni ...
- search(7)- elastic4s-search-filter模式
现在我们可以开始探讨ES的核心环节:搜索search了.search又分filter,query两种模式.filter模式即筛选模式:将符合筛选条件的记录作为结果找出来.query模式则分两个步骤:先 ...
- js点击事件,数字累加
<!doctype html><html lang="en"><head> <meta charset="utf-8&qu ...