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)的更多相关文章

  1. 【leetcode】Two Sum (easy)

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

  2. [leetcode] #112 Path Sum (easy)

    原题链接 题意: 给定一个值,求出从树顶到某个叶(没有子节点)有没有一条路径等于该值. 思路: DFS Runtime: 4 ms, faster than 100.00% of C++ class ...

  3. [array] leetcode - 53. Maximum Subarray - Easy

    leetcode - 53. Maximum Subarray - Easy descrition Find the contiguous subarray within an array (cont ...

  4. Leetcode: Split Array Largest Sum

    Given an array which consists of non-negative integers and an integer m, you can split the array int ...

  5. [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 ...

  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] 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 ...

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

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

随机推荐

  1. L9循环神经网络进阶 ModernRNN

    GRU RNN存在的问题:梯度较容易出现衰减或爆炸(BPTT) ⻔控循环神经⽹络:捕捉时间序列中时间步距离较⼤的依赖关系 RNN: Ht=ϕ(XtWxh+Ht−1Whh+bh) H_{t} = ϕ(X ...

  2. 最长上升子序列 HDU 1025 Constructing Roads In JGShining's Kingdom

    最长上升子序列o(nlongn)写法 dp[]=a[]; ; ;i<=n;i++){ if(a[i]>dp[len]) dp[++len]=a[i]; ,dp++len,a[i])=a[i ...

  3. python_ck01(虚拟环境管理)

    拖拖拉拉的毛病还是依旧如初... 断断续续坚持三天总算把虚拟环境管理部分的内容给看完了. 对三天的知识点进行梳理,方便以后回顾. ①虚拟环境安装 用pip install + 包名的方式安装,涉及到的 ...

  4. 【错误】python百分号冲突not enough arguments for format string

    query = "SELECT * FROM devices WHERE devices.`id` LIKE '%{}%'".format("f2333") d ...

  5. redis: 持久化(十二)

    RDB配置 RDB 是 Redis 默认的持久化方案.在指定的时间间隔内,执行指定次数的写操作,则会将内存中的数据写入到磁盘中.即在指定目录下生成一个dump.rdb文件.Redis 重启会通过加载d ...

  6. SMTP发邮件(直接可用)实例

    string file = "邮件测试.txt";//放在Debug下的一个txt文件. MailAddress from = new MailAddress("自己的邮 ...

  7. 移植madplay到ARM板

    一.环境和软件介绍 1.主机环境:Ubuntu16.04 2.交叉编译器: gcc version 4.4.1 (Sourcery G++ Lite 2009q3-67) 3.ARM板:kernel: ...

  8. Java IO 流 -- 数据流和对象流 DataOutputStream ObjectOutputStream

    DataOutputStream 和 ObjectOutputStream的共同点是: 1.写出后读取 2.读取顺序和写出一致 数据流操作: // 写入 ByteArrayOutputStream b ...

  9. 用python把技术文档中,每个模块系列截图生成一个动态GIF

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 最近在写技术文档的时候,发现一个问题.对于每个技术步骤,都需要一个截图,这 ...

  10. 安卓微信浏览器中window.location.href失效的问题

    最近接手一微信项目,测试功能时,发现跳转在android手机上不动了.iso系统可以正常跳转的.解决方法: window.location.href = url + '?v=' + (new Date ...