【leetcode】1. Two Sum(Python & C++)
来源:互联网 发布:用手机淘宝买东西步骤 编辑:程序博客网 时间:2024/06/05 12:03
1. Two Sum
题目链接
1.1 题目描述:
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].
1.2 解题思路:
思路一:第一个思路就是两次遍历,找到第一个元素,二次遍历其后面的元素,如果发现这两个元素的和为target,则两元素坐标push进vector。
思路二:利用map,一次遍历。在遍历时,获取target-当前遍历的元素的值,然后在map中查找是否有这个值,如果有,则将其map对应的值作为坐标值,连通遍历元素的坐标值一起push进vector;否则,则将当前遍历的这个元素的值与坐标放入map中。
1.3 C++代码:
1、思路一代码(233ms):
class Solution90 {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int>a; for (int i = 0; i < nums.size();i++) { for (int j = i + 1; j < nums.size();j++) { if (target == (nums[i] + nums[j])) { a.push_back(i); a.push_back(j); return a; } } } return a; }};
2、思路二代码(13ms):
class Solution90_1 {public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int>m; vector<int>a; for (int i = 0; i, nums.size();i++) { int tofind = target - nums[i]; if (m.find(tofind)!=m.end()) { a.push_back(m[tofind]); a.push_back(i); return a; } m[nums[i]] = i; } return a; }};
1.4 Python代码:
1、思路一代码(5865ms):
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ a=[] for i in range(len(nums)): for j in range(i+1,len(nums)): if (nums[i]+nums[j])==target: a.append(i) a.append(j) return a return a
2、思路二代码(39ms):
class Solution1(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ d={} for i in range(0,len(nums)): tofind=target-nums[i] if tofind in d: return [d[tofind],i] d[nums[i]]=i return a
阅读全文
0 0
- 【leetcode】1. Two Sum(Python & C++)
- LeetCode:1. Two Sum解法(C,C++,Jave,Python)
- 【Leetcode】【Python】【C++】1. Two Sum实现
- LEETCODE 1.Two Sum (python实现)
- Leetcode题解(Python): 1.Two Sum
- LeetCode 1.Two Sum (Python)
- 1.Two Sum Leetcode Python
- [Leetcode] 1.Two Sum @python
- LeetCode: 1. Two Sum python
- Leetcode: 1. Two Sum [python]
- [leetcode:python]1.Two Sum
- leetcode 1. Two Sum python
- LeetCode 1. Two Sum (C++)
- leetcode(一)—— Two Sum(Python/C++)
- [LeetCode]1 Two Sum(C++,Python实现)
- 【Leetcode】【python】Two Sum, Two Sum II
- LeetCode 1. Two Sum Python Solution
- 【LeetCode 1】Two Sum(Python)
- SpringMVC学习之数据绑定和表单标签库
- RNN实例(一)
- 二分图与二分图匹配概念
- MB Link Permission statement
- Spring POI 从模板生成Excel并打印
- 【leetcode】1. Two Sum(Python & C++)
- MySQL函数
- [BZOJ2934]业务
- 一些常用的网站
- 文件的相对路径和绝对路径,加载资源文件失败
- 随笔分类
- 数据库范式
- 斐波那契迭代和递归
- 神经网络与深度学习 笔记5 过度拟合和正则化