中文博客

刷题进行时

2018年1月2日 · tech

赶在Master的尾巴前开始刷题吧!

又过去了一个学期。在这个本应该是第一个学期的第二个学期期间,自己从头上了一边Data Science的各项基础课,包括算法,概率论和统计推断,却一直没有在刷题上下功夫。新年新气象,2018年就从刷题开始好了。

准备工作

LeetCode的账号早就申请好了,自己也曾经考虑报一个九章算法的课程系统刷题,不过最后都胎死腹中。打开LeetCode的网站,初步目标是将Easy先行刷一遍,当遇到问题或者觉得刷不下去之后考虑上一个九章算法的培训班。

Reference

这里是复习记录,遇到问题和有想法的时候会在这里更新。


Week 1: 1/1/2018 - 1/7/2018

1. Two Sum (约用时1.5h)

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.

问题

感悟

附录:最终的code

class Solution:
    def twoSum(self, nums, target):
        my_dict = {item:index for index,item in enumerate(nums)} # Create dict with item:index key-pair.
        if target % 2 == 0 and nums.count(target/2) == 2: # Edge case: two identical elements with target/2 value?
            return [i for i,val in enumerate(nums) if val==target/2] # return list of indexes. See reference
        else:
            for index, item in enumerate(nums): # for all elements in the list, O(n) RT 
                seek_number = target-nums[index] # Get the seek number
                if seek_number != target/2 and seek_number in my_dict: # avoid the edge case
                    return [index, my_dict[seek_number]]
                    break

(后续内容已省略,仅作为迁移示例)