zoukankan      html  css  js  c++  java
  • 1. Two Sum

    去年听公司大神说起leetcode,当时是实习生的我还不知道leetcode是什么,后来得知是刷算法题的网站,也并不在意,以为作为一个学渣我的算法几乎为0,转眼间工作一年了,大神离开了,去了蚂蚁金服,让人羡慕,哈哈,也许每个人都有离开的那一天,真的担心离开了会找不到自己满意的工作,不太像一辈子做一个只会写简单的代码的程序猿,打算从今天起也开始努力,开始自己的刷题之旅。先从简单的开始。

    题目1:

    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].

    我用的是python3
    个人解法:暴力破解:
    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            for i in range(len(nums)):
                if (target - nums[i]) in nums[i+1:len(nums)]:
                    if target== 2*nums[i]:
                        return [i, len(nums)-1-nums[::-1].index(target - nums[i])]
                    else:
                        return [i, nums.index(target - nums[i])]

    没什么好解释,觉得和算法关系并不大,可能是我选择easy的题的关系吧。

    提交代码后看了 答案有很多方式,例如hash-map,现将所有值的下标和对应的值当成键值存进去,然后找出对应的下标返回,个人感觉其实思路差不多,只是取值的方式不太一样,不过在大学时候写过点java,看了别人的code也觉得有些收获,不经常写hash-map也理解了一下,拓宽以后的结题思路吧。

    先定个小目标,目标一个月50道吧。

  • 相关阅读:
    利用matlab给图像加高斯噪声
    频谱分析代码片段2
    相关性分析代码片段2
    相关性分析代码片段
    频谱分析代码片段
    大脑提取每一个体素26领域的matlab代码
    当前所看论文记录
    论文阅读笔记
    余弦距离、欧氏距离和杰卡德相似性度量的对比分析 by ChaoSimple
    Container With Most Water
  • 原文地址:https://www.cnblogs.com/jingtyu/p/7133182.html
Copyright © 2011-2022 走看看