水题一个,直接用冒泡做了,但是很奇怪的是用vector<int> iterator
和size_t
的运行时间差了很多。前者直接就超时了,后者AC。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
size_t n = nums.size();
vector<int> res(2);
for (int i=0; i<n; i++)
for (int j=i+1; j<n; j++) {
if(nums[i]+nums[j]==target) {
res[0]=i;
res[1]=j;
return res;
}
}
return res;
}
};
下面是python代码:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
for i in range(n):
for j in range(i+1, n):
if nums[i]+nums[j] == target:
return i,j