【leetcode】Two Sum
来源:互联网 发布:软件设计师下午题型 编辑:程序博客网 时间:2024/05/22 14:31
题目: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].
import java.util.HashMap;public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ map.put(nums[i], i); } int a = 0; int b = 0; for(int i=0;i<nums.length;i++){ a = i; int number = target-nums[a]; if(map.get(number)!=null&&map.get(number)!=a){ b = map.get(number); break; } } //System.out.println(a +" "+b); int[] res = new int[2]; res[0] = a<b?(a):(b); res[1] = a>b?(a):(b); //System.out.println(res[0] +" "+res[1]); return res; } public static void main(String[] args){ int[] s = new int[]{3,2,4}; new Solution().twoSum(s, 6); }}
0 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- 最大连续数列的和-SSL 1461
- css之页面布局的w3c盒子模型
- 12306用的是SRCA的根证书——原文标题:在线买火车票为什么要【安装根证书】?
- 蓝桥杯 ADV-119 算法提高 6-9删除数组中的0元素
- android studio使用Lambda表达式的正确姿势
- 【leetcode】Two Sum
- Error:Execution failed for task ':app:transformClassesAndResourcesWithProguardForRelease'. > Job fai
- 蓝桥杯 ADV-127 算法提高 日期计算
- linux 常用
- 关于Python学习中的一段代码的解读:data_dict = {h: v for h, v in zip(header, zip(*values))}
- 继承详谈
- 在Ubuntu14.04中安装谷歌chrom浏览器
- poj2240(最短路径 Floyd算法)
- 蓝桥杯 ADV-132 算法提高 笨小猴