leetcode-two sum
来源:互联网 发布:华硕a555lbios怎么优化 编辑:程序博客网 时间:2024/06/15 23:32
lz决定增长自己的算法水平了,因为自己不可能一直做低层次的编写代码工作。lz最近在关注牛客网,他真的是一个很棒的网站,在这里更加看清了自己和外面的差距,同时也找到了解决差距的办法。其中就有leetcode,好了闲话少叙,开始记录我的LeetCode!
1. Two Sum:
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].
代码:
/*** * leetcode 1.two sum * 题意:给定一个整数数组nums和一个整数target,要你求出nums数组哪两个元素相加等于target,并返回两个元素的下标 * 约束条件:1.两个元素的下标不能相同,即不能是同一个元素 2.nums总能有正解 * 解题思路:既然两个元素不能相同,则用map来保存数组元素和下标,键为数组元素,值为数组下标。循环遍历nums,将当前数组元素放入到map中,判断如果map中含有target-nums[i]的键,有则nums[i]就是第二个元素,target-nums[i]就是第一个元素 * @param nums * @param target * @return */
public int[] twoSum(int[] nums, int target) {int[] result = new int[2];Map<Integer, Integer> map = new HashMap<Integer, Integer>();for (int i = 0; i < nums.length; i++) {if (map.containsKey(target - nums[i])) {result[1] = i;result[0] = map.get(target - nums[i]);return result;}map.put(nums[i], i);}return result;}
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
- 如何调试shell脚本
- Discuz!论坛教程之如何禁止/允许用户编辑自己发布的帖子
- 关于前端多选框的相关问题
- caffe笔记(一)--官方教程整理
- JavaScript 使用误区
- leetcode-two sum
- 【LeetCode】Binary Tree Tilt 解题报告
- [leetcode 33]Search in Rotated Sorted Array
- 欢迎使用CSDN-markdown编辑器
- Linux内核目录结构
- 严重: Error configuring application listener of class org.springframework.web.context.ContextLoaderLis
- 安卓智能地图开发与实施七:在线业务图层(浏览查询)
- Git 常用命令大全
- 微赞框架封装好的地址联动