一 、算法刷题LEETCODE第一题数组求和twoSum
给一个整形数组sums,给定一个目标值target,编写函数twoSum遍历数组使得数组中两数的和等于target,此时输出这两个数的下标。
二、英文原文
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
三、测试描述
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
四、规范要求
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
五、博主参考代码
本人用C++写的代码,投石问路,仅供参考。
class Solution{
public:
vector <int> twoSum(vector<int> &nums, int target) {
vector <int> indic;
int a=0,b=0;
indic.resize(2);
int n=nums.size();
for (int i= 0;i < n-1;i++)
{
for (int j=i+1;j < n;j++)
{
if ( target == nums[i]+ nums[j] )
{
a = i;
b = j;
break;
}
}
if(b!=0) break;
}
if(b==0)
cout<<"Could not find the two numbers!"<<endl;;
indic[0] = a;
indic[1] = b;
return indic;
}
};
六 测试结果
https://blog.youkuaiyun.com/Elon_Zac?type=blog
七 LEETCODE问题的难点
1.光大观众没有完整的主函数无法知道如何调用,故会出现不可预知的问题,导致本地编译成功,提交到LEETCODE缺编译不通过
八 测试用完整函数
该程序利用容器可以动态由键盘随意输入整形可变长度数组,直至回车自动退出数组输入,进行测试
#include <iostream>
#include<vector>
#include<string>
using namespace std;
//https://blog.youkuaiyun.com/Elon_Zac?type=blog
class Solution {
public:
vector<int> twoSum(vector<int> &x, int y);
Solution(vector<int> &x, int y);
private:
vector <int> nums;
int target;
};
Solution::Solution(vector<int> &x, int y){
vector<int>::iterator it;
target= y;
for(it=x.begin();it<x.end();it++){
nums.push_back(*it);
//cout<<*it<<endl;
}
}
vector <int> Solution::twoSum(vector<int> &x, int y) {
vector <int> indic;
int a=0,b=0;
indic.resize(2); //固定长度的容器需要resize(n)确定长度,否则容器长度始终是0,除非用push.back()增长
int n=nums.size();
for (int i= 0;i < n-1;i++)
{
for (int j=i+1;j < n;j++)
{
if ( target == nums[i]+ nums[j] )
{
a = i;
b = j;
break;
}
}
if(b!=0) break;
}
if(b==0)
cout<<"Could not find the two numbers!"<<endl;;
indic[0] = a;
indic[1] = b;
return indic;
};
int main(void)
{
vector <int> nums,index;
vector<int>::iterator it;
int target ,intNUM;
string s1("Given an array of integers nums and an integer!");
cout<<s1<<endl; ///STL默认是不会直接输出字符串的 string头文件重载之后是可以用cout直接输出字符串的
//https://blog.youkuaiyun.com/Elon_Zac?type=blog
for (int j=1;;j++) { /// 动态从键盘写入容器
cin>>intNUM;
nums.push_back(intNUM);
if ( cin.get() == '\n' ) break;
}
cout<<"Given an integer target!"<<endl;
cin>>target;
Solution A( nums, target);
index = A.twoSum(nums, target);
cout<<"The indices of the two numbers such that they add up to target!"<<endl;
cout<<"["<< index[0]<<","<<index[1]<<"]"<<endl;
//
https://blog.youkuaiyun.com/Elon_Zac?type=blog
system("pause");
return 0;
}
以码会友,算法论剑!