python求数组中两数之和为指定值的下标位置。 --------------------------------------------------- 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数的位置。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 示例:: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 我们使用循环遍历来进行解答,并且使用unittest对接口功能进行测试, 答案如下 :: import unittest class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ i = 0 j = 0 for num1 in nums: for num2 in nums: if( num1+num2 == target): return (i, j) j += 1 i += 1; class TestTwoSumFunc(unittest.TestCase): """Test revert""" def test_twoSum(self): """Test method add(a, b)""" s = Solution() self.assertEqual((0,1), s.twoSum([2, 7, 11, 15], 9)) if __name__ == '__main__': unittest.main() 该算法实现的复杂度为O(n^2), 复杂度分析: * 时间复杂度:O(n^2), 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n) 的时间。 因此时间复杂度为 O(n^2)。 * 空间复杂度:O(1)。 参考了leetcode.com