您的位置:首页 > 其它

leetcode记录

2018-03-06 20:23 169 查看
主要熟悉该平台,以及重新熟悉C++的使用.

Two-Sum

题目:给定义一个数组,以及一个目标和,求数组中哪两个数字相加为该目标和.
注意点:时间复杂度!

(1)两重for循环查找.

           时间复杂度:O(n^2),空间复杂度:O(1)
            对每个元素nums[i],查找可能满足的差值nums[j](在整个数组内查找,花费时间为O(n))
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}

(2)快排.同时使用头尾指针.+ 一遍查找 (T(O(nlogn)),S(O(1))

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> tmp;
int a=0,b=nums.size()-1,sum=0,i;
vector<int> ids;

sort(tmp.begin(),tmp.end());
while(a<b)
{
if(tmp[a] + tmp[b] >target) b--;
else if(tmp[a] + tmp[b] <target) a++;
else break;
}
for(i=0;i<nums.size();i++)
{
if(nums[i]==a) ids.push_back(a);
else if(nums[i]==b) ids.push_back(b);

}
return ids;
}
};

#python实现class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
a = 0
b = len(nums)-1
tmp = sorted(nums)
ids = []
while a<b:
if (tmp[a]+tmp[b]>target):
b = b-1;
elif (tmp[a]+tmp[b]<target):
a = a+1;
else: break;
for i in range(len(nums)):
if (nums[i] == tmp[a] or nums[i] == tmp[b]) : #python : | -> or
ids.append(i)
return ids
#return [nums.index(tmp[a]),nums.index(tmp[b])] bug:repeat-element

(3)HashMap映射   + 一遍查找(T(O(n)),S(O(n)))

   减少每个元素在寻找差值的时间:提前建立数组中值与下标的映射关系;查找差值只需要O(1)
          bug点:注意判断该差值是否为本身.([3 2 4],6  例子中,6=3+3,可能会给出0,0的下标输出,导致错误)public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: