LeetCode 1. Two Sum
来源:互联网 发布:淘宝兔家公子有假货吗 编辑:程序博客网 时间:2024/06/10 21:08
问题描述:
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].
问题分析:
给定一个无需的数组nums[],每个值都不一样。给定一个数target。求出两个数的和等于target,要求输出这个两个数的下标。
可以遍历这个数组,先判断target-nums[i]是否在map中,如果在直接返回下标,否者将每个数以及数的下标添加到map中。时间复杂度O(n).
代码实现
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> numIndexMap = new HashMap<Integer, Integer>(nums.length); for (int i = 0; i < nums.length; i++) { int nextValue = target - nums[i]; if (numIndexMap.get(nextValue) != null) { return new int[]{numIndexMap.get(nextValue), i}; } numIndexMap.put(nums[i], i); } return new int[2]; }
阅读全文
0 0
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 【LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- leetcode 1. Two Sum
- [leetcode] 1. Two Sum
- leetcode 1. Two Sum
- Leetcode- 1. Two Sum
- LeetCode-1.Two Sum
- Leetcode 1. Two Sum
- C++中的容器(一)
- mif文件的生成
- 【java】Mybatis返回int类型为空时报错 attempted to return null from a method with a primitive return type (int)
- 【Redis源码剖析】
- JavaWeb学习----JSP简介及入门(含Eclipse for Java EE及Tomcat的配置)
- LeetCode 1. Two Sum
- 利用Linux命令行进行文本按行去重并按重复次数排序yes
- jquery.validate.min.js 插件
- 国密SM9算法测试数据
- 物理层-传输介质
- C语言程序设计习题 1-8 编写一个统计空格,制表符与换行符个数的程序
- 项目开发中遇到的问题及解决办法
- 《算法(第四版)》 1.3.29 环形链表
- linux VFS讲解