Leetcode 1. Two Sum
来源:互联网 发布:贵州6频道网络电视 编辑:程序博客网 时间:2024/05/16 18:06
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].
题意就不说了,很简单明了,下面谈一下第一个解法就是直接寻找,也即暴力遍历,最初的想法是两层循环实现。但是这个做法造成时间复杂度是O(n^2),后来我想到使用Map来加速查询效率,优化到O(n),
这道题给我的最大的启发就是在大量的遍历查询的出现下,可以使用Set或者Map等关联容器来加速查询效率,这是典型的空间换时间。
代码如下:
import java.util.HashMap;import java.util.Map;public class Solution { /* * 使用Map加速查找效率 * */ public int[] twoSum(int[] nums, int target) { int []res={0,0}; Map<Integer, Integer> map=new HashMap<Integer, Integer>(); for(int i=0;i<nums.length;i++) map.put(nums[i], i); for(int i=0;i<nums.length;i++) { int index=map.getOrDefault(target-nums[i], -1); if(index>=0 && index!=i) { res[0]=i; res[1]=index; break; } } return res; } /* * 遍历求解 * */ public int[] twoSum111(int[] nums, int target) { int []res={0,0}; boolean find=false; for(int i=0;i<nums.length;i++) { int a=nums[i]; int b=target-a; for(int j=1+i;j<nums.length;j++) { if(nums[j]==b) { find=true; res[1]=j; break; } } if(find) { res[0]=i; break; } } return res; }}
下面是C++答案
#include <iostream>#include <vector>#include <map>using namespace std;//注意使用Map等数据结构class Solution{public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; map<int,int> myMap; for(int i=0;i<nums.size();i++) myMap[nums[i]]=i; for(int i=0;i<nums.size();i++) { int one=target-nums[i]; map<int,int>::iterator iter = myMap.find(one); if(iter!= myMap.end() && iter->second != i) { res.push_back(i); res.push_back(iter->second); break; } } return res; }};
阅读全文
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
- iOS 图片抖动
- spring中IoC中的自动装配
- 网站利用腾讯云服务器使用kangle组建中间源实现无限抗DDOS攻击,就算真实源IP暴露也不怕,配合百度云加速CDN完美0误封抗CC攻击,0回源,最低成本不买高防解决大量攻击的问题
- Maven构建跳过单元测试
- 《捕鱼游戏》隐私政策
- Leetcode 1. Two Sum
- linux的ls命令详解(二)
- 计算机网络体系结构——物理层
- java基础之IO流
- 解决 Python 出现的UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9
- opencv标准霍夫变换检测直线以及描绘每条线段中pt1、pt2点的确定
- Efficient Inference in Fully Connected CRFs with Gaussian Edge Potentials之python代码运行
- ubuntu16.04 u 盘安装
- js typeof表达式