1. Two Sum
  • Description
  • Brute-Force
    O(n2)
    #!/usr/bin/python
    '''LeetCode question 1
    '''
    
    def twoSum(nums, target):
        n = len(nums);
        for i in xrange(n-1):
            for j in xrange(i+1, n):
                if (nums[i] + nums[j]) == target:
                    return i, j
    
    def main():
        nums = [2, 7, 11, 15]
        target = 9
    
        index = twoSum(nums, target)
    
        if index:
            print index
        else:
            print 'No pair has been found for target %d' % target
    
    if __name__ == '__main__':
        main()
    			
    Hash
    O(n)
    #!/usr/bin/python
    '''LeetCode question 1
    '''
    
    def twoSum(nums, target):
        d = {}
        for indx, ele in enumerate(nums):
            if d.has_key(target-ele):
                return (d[target-ele], indx)
            else:
                d[ele] = indx
    
    def main():
        nums = [2, 7, 11, 15]
        target = 9
    
        index = twoSum(nums, target)
    
        if index:
            print index
        else:
            print 'No pair has been found for target %d' % target
    
    if __name__ == '__main__':
        main()
    			
    #!/usr/bin/python
    '''LeetCode question 1
    '''
    
    def twoSum(nums, target):
        d = {}
        for indx, ele in enumerate(nums):
            if d.has_key(ele):
                return d[ele], indx
            else:
                d[target-ele] = indx
    
    def main():
        nums = [2, 7, 11, 15]
        target = 9
    
        index = twoSum(nums, target)
    
        if index:
            print index
        else:
            print 'No pair has been found for target %d' % target
    
    if __name__ == '__main__':
        main()