Leetcode 001

题目:给定一个整数数组nums 和一个目标值target,在nums中找到和为目标值的两个整数,并返回它们的数组下标

solution 1: 采用暴力搜索的方法进行遍历

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)-1):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j] == target:
                    return i,j 

solution 2:采用字典的方法模拟哈希表(这里我也不清楚什么是哈希表)

    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        index_dict = {}
        for inx,num in enumerate(nums):
            
            if (target-num) in index_dict:
                return index_dict[target-num],inx  
            index_dict[num] = inx

相比第一种方法,这里的第二种方法时间上块了很多。另外一种解法是先遍历一遍整个数组然后,然后在字典里直接遍历。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容