美文网首页看场电影
2018-06-02 1 Two Sum

2018-06-02 1 Two Sum

作者: 二山三人 | 来源:发表于2018-06-04 06:40 被阅读18次

1. O(nlogn)

First sort the list. Then use two pointers from beginning and end to search.
'''

def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    sorted_nums = nums[:]
    sorted_nums.sort()
    len_list = len(nums)
    
    i = 0
    j = len_list - 1
    num_1 = sorted_nums[i]
    num_2 = sorted_nums[j]
    while sorted_nums[i] + sorted_nums[j] != target:
        if sorted_nums[i] + sorted_nums[j] > target:
            j -= 1
        elif sorted_nums[i] + sorted_nums[j] < target:
            i += 1
        num_1 = sorted_nums[i]
        num_2 = sorted_nums[j]
        
    num_1_idx = nums.index(num_1)
    if num_1 == num_2:
        num_2_idx = nums.index(num_2, num_1_idx+1)
    else:
        num_2_idx = nums.index(num_2)
    
    return [num_1_idx, num_2_idx]

'''

2. O(n)

Use dictionary to store the value2index. Iterate once.
'''

def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    num2idx_dict = {}
    len_list = len(nums)
    for i in xrange(len_list):
        complement = target - nums[i]
        if complement in num2idx_dict:
            return [num2idx_dict[complement], i]
        num2idx_dict[nums[i]] = i

'''

相关文章

  • 2018-06-02 1 Two Sum

    1. O(nlogn) First sort the list. Then use two pointers fr...

  • LeetCode 1. Two Sum (Easy)

    LeetCode 1. Two Sum (Easy) LeetCode 1. Two Sum (Easy) 原题链...

  • 1. Two Sum

    1. Two Sum 题目:https://leetcode.com/problems/two-sum/ 难度: ...

  • leetcode hot100

    1. Two Sum[https://leetcode-cn.com/problems/two-sum/] 字典(...

  • leetCode #1

    #1. Two Sum

  • LeetCode之Swift

    1.Two Sum (Easy)

  • X Sums

    Two Sum It is not easy to write Two-Sum right for the fir...

  • 1 two sum

    title: Two Sumtags:- two-sum- simple- hash- No.1- integer...

  • 1、Two Sum

    题设 要点 Hash表,将双重循环的O(n^2)降到O(n) 排序+首尾指针,不断移动 该题其实就是一个很简单的搜...

  • 1 Two Sum

    Given an array of integers, return indices of the two num...

网友评论

    本文标题:2018-06-02 1 Two Sum

    本文链接:https://www.haomeiwen.com/subject/rvodsftx.html