[leetcode]-[Two Sum]-python实现
2015-04-07 21:35
423 查看
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
https://leetcode.com/problems/two-sum/
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
https://leetcode.com/problems/two-sum/
#!/usr/bin/env python # coding=utf-8 class Solution: # @return a tuple, (index1, index2) def twoSum(self,num,target): map = {} j = 1 for i in num: if (not map.has_key(i)): map[i]=[]; map[i].append(j); j = j + 1 for i in num: ta = target - i j = map[i][0] if map.has_key(ta): if i == ta: if len(map[ta])> 1: return j, map[i][1] else: if j > map[ta][0]: j, map[ta][0] = map[ta][0], j return j,map[ta][0] if __name__ == '__main__': s = Solution() num = [0, 3 , 4, 0] target = 0 reults = s.twoSum(num, target) print reults
相关文章推荐
- leetcode 【 Two Sum 】python 实现
- 【Leetcode】【Python】【C++】1. Two Sum实现
- [LeetCode]3 Longest Substring Without Repeating Characters (C++,Python实现)
- [LeetCode]5 Longest Palindromic Substring(C++,Python实现)
- leetcode 【 Sort List 】 python 实现
- leetcode 【 Partition List 】python 实现
- leetcode 【 Swap Nodes in Pairs 】python 实现
- [LeetCode]1 Two Sum(C++,Python实现)
- leetcode 【 Add Two Numbers 】 python 实现
- leetcode 【 Linked List Cycle II 】 python 实现
- leetcode 【 Reverse Words in a String 】python 实现
- leetcode 【 Copy List with Random Pointer 】 python 实现
- LeetCode 2. Add Two Numbers (C++/python/js实现)
- leetcode 【 Remove Nth Node From End of List 】 python 实现
- leetcode 【 Linked List Swap Nodes in Pairs 】 python 实现
- leetcode 【 Insertion Sort List 】 python 实现
- [LeetCode]4 Add Two Numbers(C++,Python实现)
- 【LeetCode with Python】 Two Sum
- leetcode 【 Remove Duplicates from Sorted List II 】 python 实现
- leetcode 【 Reverse Nodes in k-Group 】 python 实现