1. Two Sum
来源:互联网 发布:cnnic数据 编辑:程序博客网 时间:2024/06/07 09:40
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 thesame element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
Solution:
Tips:
1. How to record index of array.
2.
2.1 sort array, pick out a number from left and then pick out a number from right of the array. compare target with sum of left number and right. if sum equals to target stop, else if sum less than the target left forward one step, otherwise right step back.
2.2 try to use an appropriate data structure, such as hashmap.
Java Code
public class Solution { public int[] twoSum(int[] nums, int target) { // key --> value (val, idx) Map<Integer, Integer> mii = new HashMap<>(); int leftIdx = 0; int rightIdx = 0; for (int i = 0; i < nums.length; i++) { rightIdx = i; if (mii.containsKey(target - nums[i])) { leftIdx = mii.get(target - nums[i]); break; } mii.put(nums[i], i); } int[] result = {leftIdx, rightIdx}; return result; }}
0 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- windows系统口令配置文件是
- 方格红与黑
- 【九度OJ】题目1192:回文字符串 解题报告
- CSS——背景
- 快速幂取余 总结
- 1. Two Sum
- 将“EntityFramework 6.1.3”更新到“EntityFramework 5.0.0”失败。找不到与“EntityFramework 5.0.0”兼容的“EntityFramework.
- E-养兔子
- wait和waitpid详解
- 官网页面总结
- RDIFramework.NET ━ .NET快速信息化系统开发框架 V3.2-新增锁定用户与解除锁定用户的功能
- 查询两门及两门以上不及格同学的平均分
- 最长回文子串(练习...)
- MATLAB读取和显示obj文件的数据