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.数组值和下标互换是一种常用的技巧,不过只对整数有用;

最新文章

  1. 7月07日——[HouseStark] 团队简介
  2. JS魔法堂:函数重载 之 获取变量的数据类型
  3. [玩转微信平台]XML的格式化- 如何去掉XML 文档头和命名空间
  4. 泛型类型转为DataTable类型
  5. 一个可视化的retrospective网站
  6. Java学习笔记--链表
  7. 利用AD采集获取外部温度传感器的值
  8. 基于MVC的网站和在线教育系统
  9. 【剑指Offer】只出现一次的字符
  10. C# Redis安装 使用教程
  11. tips___代码规范
  12. SDN2017 第二次作业
  13. Java基础91 mysql的用户权限设置问题
  14. 读think in java有感
  15. Asp.net自定义控件系列(一)
  16. hdoj1160 DP--LIS
  17. 57. Insert Interval (Array; Sort)
  18. LeetCode——Unique Binary Search Trees
  19. mac 终端命令行操作
  20. redis在Linux上的部署和jedis简单使用

热门文章

  1. 数论-质因数(gcd) UVa 10791 - Minimum Sum LCM
  2. 令人迷惑的Gamma
  3. win7下delphi中的help文档问题
  4. 深度学习之文本分类模型-前馈神经网络(Feed-Forward Neural Networks)
  5. PHP函数:debug_backtrace
  6. Linux学习笔记(二)文件操作命令
  7. [复现]GXY2019
  8. BJDCTF 2nd web
  9. C# 基础知识系列- 12 任务和多线程
  10. react: typescript system params optimize