【Leetcode】【Python】【C++】1. Two Sum实现
来源:互联网 发布:淘宝天猫投诉电话人工 编辑:程序博客网 时间:2024/05/16 17:36
题目:
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].
思路:
temp数组存放nums数组中对应位置的需要值,e.g. nums中第一个元素nums[ 0 ]为2,那么这个元素对应target的目标值为9-2=7,那么把这个值放入temp中即temp[ 0 ];当遍历到nums中的元素nums[ j ] 和temp中的某个元素temp[ i ]相等时,也就意味着前面我们需要的元素已经找到,那么此时,temp[ i ] + nums[ j ] = target。在本例中,nums中遍历到的下一个元素是nums[ 1 ] = 7, 他和temp[ 0 ]相等,也就是说我们找到了相加为target所需要的值。这时候nums[ 0 ] + nums[ 1 ] = 9,程序应返回i,j,这里为0,1.
实现:
#include#include using namespace std;class Solution {public:vector twoSum(vector & nums, int target){vector temp;int num = nums.size();vector result;temp.push_back(-9999);for (int i = 0; i < num; i++){for (int j = 0; j < temp.size(); j++){if (nums[i] == temp[j]){result.push_back(j-1);result.push_back(i);return result;}}temp.push_back(target - nums[i]);}}};int main(){vector res;vector test;int target = 0;test.push_back(0);test.push_back(4);test.push_back(3);test.push_back(0);Solution A;res = A.twoSum(test, target);for (int i = 0; i < res.size(); i++){cout << res[i] << endl;}cin.get();return 0;}
阅读全文
0 0
- 【Leetcode】【Python】【C++】1. Two Sum实现
- [LeetCode]1 Two Sum(C++,Python实现)
- 【leetcode】1. Two Sum(Python & C++)
- LEETCODE 1.Two Sum (python实现)
- LeetCode 1. Two Sum(c语言实现)
- leetcode two sum python 实现
- [leetcode]-[Two Sum]-python实现
- LeetCode:1. Two Sum解法(C,C++,Jave,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 C++ python实现
- leetCode之Two Sum python实现
- LeetCode-1-Two Sum(C语言实现)
- mariadb
- struts2 控制器
- Oracle-SQL ALTER语句写法
- Caffe2
- Android ImageLoader框架下图片缓存的预处理情境
- 【Leetcode】【Python】【C++】1. Two Sum实现
- 数据结构——栈(顺序栈)
- js开发:原生js实现图片延迟加载
- 文件打开和保存对话框
- Transfrom动画
- 为什么要使用Kotlin呢
- Kotlin
- MySQL高可用架构之MHA
- Java 的8种基本类型和3种引用类型