zoukankan      html  css  js  c++  java
  • 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       
  • 相关阅读:
    快捷键打开远程桌面
    织梦Dedecms后台登陆密码忘记怎么办?
    Windows curl开启注意事项
    Composer教程
    composer.json和composer.lock有什么区别?
    Web.config 文件例子
    win10回收站右键有2个“CCleaner”怎么删除
    sublime快捷键
    Json 文件注意事项
    加入购物车流程
  • 原文地址:https://www.cnblogs.com/bigdata-stone/p/10217178.html
Copyright © 2011-2022 走看看