leetcode第一题(easy)
第一题:题目内容
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.
Example: Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例: 给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
今天做了leetcode的第一道题,题意很简单,就是给定一组数和一个目标值,从这组数中找到两个数加起来等于目标值,输出目标值的下标。
刚刚见到这道题,没过脑,直接使用暴力遍历,两个循环嵌套,逐个进行相加运算,复杂度是O(n^2)
def twoSum( nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ l=list() for i in range(len(nums)): print('i=',i) for j in range(i+1,len(nums)): print('j=',j) if nums[i]+nums[j]==target: l.append(i) l.append(j) return l
查找了别人写的之后感觉还是大神厉害的哈哈,自己提交之后AC了
def twoSum( nums, target): sum=[] for i in range(len(nums)): one = nums[i] second = target-nums[i] if second in nums: j = nums.index(second) if i!=j: sum.append(i) sum.append(j) return sum