Easy 1题 Two Sum
来源:互联网 发布:mysql 分组 字段累加 编辑:程序博客网 时间:2024/05/16 09:09
问题:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
很容易用O(N^2)解,但是没想到用hash表,so the hint is just like below...
public class Solution { public int[] twoSum(int[] nums, int target) { /* int i,j; int result[]=new int[2]; for(i=0;i<=nums.length-1;i++) { for(j=i+1;j<=nums.length-1;j++) { if(target==nums[i]+nums[j]) { result[0]=j; result[1]=i; break; } } } return result; */ int[] result = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0;i<=nums.length-1;i++) { if(map.containsKey(target-nums[i]))//若找到则结束,返回存储的下标+1和当前下标+1. { result[1]=i+1; result[0]=map.get(target-nums[i]); //找回原来存的下标 break; } else//若找不到则将<nums[i], i>加入映射表。 { map.put(nums[i], i+1); } } return result; }}
0 0
- Easy 1题 Two Sum
- #1 Two Sum(Easy)
- Leetcode #1 Two Sum (easy)
- Leetcode #1 - Two Sum - Easy
- LeetCode 第1题 Two sum (easy)——python
- Easy 371题 Sum of Two Integers
- Easy 1 Two Sum(1)
- LeetCode OJ 1 Two Sum [Easy]
- week1-leetcode #1-Two Sum[Easy]
- LeetCode-Easy刷题(1) Two Sum
- Leetcode[Easy] - Two Sum
- 【Leetcode】Two sum(easy)
- Two Sum(easy)
- Two Sum(easy)
- 【Easy】1. Two Sum
- leetcode Two Sum easy
- [Easy]Two Sum
- 1. Two Sum easy
- IO技术(四)转换流
- mysql 设置初始密码
- css-样式优先级算法
- HTML5对浏览器的支持以及创建自己的元素
- 2.自己动手写Java Web框架-读取配置
- Easy 1题 Two Sum
- mysql悲观锁总结和实践
- HDU 5868 Different Circle Permutation(dp+polya+矩阵快速幂+欧拉函数)
- IO技术(五)流的使用规律和键盘读入数据
- 《Java编程思想第四版》笔记---16章 数组
- Google 2016面试题
- 虚拟机NAT方式解决主机PING不同虚拟机的问题
- MongoDB在CentOS下的装配、启动和配置
- 国内三大云数据库测试对比