LeetCode刷题 | NO.001

最近开始跟着一个公众号在刷leetcode啦,希望坚持下去,都是大佬的思路了。

大佬公众号:小詹学python

No.1 Two Sum

原题:

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.

 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用

最先可以想到是用二重循环,但是会发现用例超时

def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """

    result = []
    for i in range(len(nums)):
        for j in range(i+1,len(nums)):
            if nums[i] + nums[j] == target:
                result.append(i)
                result.append(j)
                return result

由于有且仅有一个解,我们通过判断target与列表内的元素差值判断该元素是否在列表中

def twoSum(self,nums , target):
    result = []
    for i in range(len(nums)):
        number =  target - nums[i]
        if number in nums:
            j = nums.index(number)
            if i != j:
                result.append(i)
                result.append(j)
                return result

第二个改进方法是用字典存储,创建字典将Nums中的值和序号对应,另一个字典则存储target-nums的值,判断该值是否在nums中,并且返回相应的索引值

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        result = []
        num_dictionary = {nums[i]:i for i in range(len(nums))}
        num_dictionary2 = {i:target - nums[i] for i in range(len(nums))}

        for i in range(len(nums)):
            j = num_dictionary.get(num_dictionary2.get(i))
            if (j is not  None) and (j != i):
                result = [i,j]
                break
        return result

C++

简单介绍:

在map中:

——使用count,返回的是被查找元素的个数。如果有,返回1;否则,返回0。注意,map中不存在相同元素,所以返回值只能是1或0。

——使用find,返回的是被查找元素的位置,没有则返回map.end()。

在vector中:vector简单理解为动态一维数组push_back作用是在这个一维数组尾部插入一个元素。

class Solution {
public:      
    vector<int> twoSum(vector<int> &numbers, int target) {
        unordered_map<int, int> m;
        vector<int> result;
        for(int i=0; i<numbers.size(); i++){
            // not found the second one
            if (m.find(numbers[i])==m.end() ) { 
                // store the first one poisition into the second one's key
                m[target - numbers[i]] = i; 
            }else { 
                // found the second one
                result.push_back(m[numbers[i]]);
                result.push_back(i);
                break;
            }
        }
        return result;
    }
};

 //哈希表

class Solution{
public:
    vector<int> twoSum(vector<int>& nums, int target) {  
        vector<int> result;  
        map<int, int> m;//键值为nums的值,变量值为nums下标  
  
        for (int i = 0; i < nums.size(); ++i) {  
            if (m.count(nums[i]) != 0) {  
                result.push_back(tmpmap[nums[i]]);  
                result.push_back(i);  
                break;  
            }  
            m[target - nums[i]] = i;  
        }  
        return result;  
} 
};

猜你喜欢

转载自blog.csdn.net/qq_35924276/article/details/81224891