当前位置 博文首页 > Two Sum_让代码改变世界:LeetCode 1
这是leetcode中的第一题,题目并不是很难,但对于我这个算法小白来说却也够了。废话不多说了,直接上题
原题:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
题目的意思大概是给定一个整数数组,和一个目标和,要求从数组中找出两个数,使他们的和为目标和,记录这两个数的下标。
自己编的代码:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> tempVec;
int index1=1;//记录下标
bool flag=false;//标识是否找到
for(vector<int>::iterator iter1=nums.begin();
iter1!=nums.end()&&flag==false;++iter1,++index1){
int index2=index1+1;if(*iter1>=target) continue;
for(vector<int>::iterator iter2=iter1+1;
iter2!=nums.end();++iter2,++index2){
if(*iter2>=target) continue;
if((*iter1+*iter2)==target){
tempVec.push_back(index1);
tempVec.push_back(index2);
flag=true;//找到了
}
}
}
return tempVec;
}
};
这个就不多解释了,相信大家都能看懂,程序的评判结果为运行超时,然后又找了一个大神的代码,代码用C++实现用时8ms,在排名中比较靠前因此被拿来学习(PS:谢谢leetcode上的大神 bobyaoswager提供的代码)。当然还有更快的实现方法,但这里主要是讲明概念,所以没有必要去找一个特定的最快解法
int compare(const void* a,const void* b)
{
return *(int*)a - *(int*)b;//返回*a-*b
}
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int>index;
int len = nums.size();//数组大小
int *temp = new int[len];
for(int i = 0; i < len; i++)
temp[i] = nums[i];//把数据复制到数组
qsort(temp,len,sizeof(int),compare);//快排
int left = 0;
int right = len - 1;
while(left < right)
{
if((temp[left] + temp[right]) > target)
right--;
else if((temp[left] + temp[right]) < target)
left++;
else
break;
}
for(int i = 0; i < len; i++)
{
if(nums[i] == temp[left] || nums[i] == temp[right])
index.push_back(i + 1);
}
delete[] temp;
return index;
}
};
看完这个结果我是挺诧异的,这数据倒来倒去的不浪费时间吗?怎么会这么快呢?由于本人不是计算机专业出身,所以只能去恶补了一下时间复杂度这个概念。通过简单的了解,学到了如下知识: