TreeviewCopyright © aleen42 all right reserved, powered by aleen42
1. 两数之和
https://leetcode-cn.com/problems/two-sum/
Java
import java.util.Arrays;
class Solution {
public int[] twoSum(final int[] nums, final int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("no solution");
}
public static void main(final String[] args) {
System.out.println(Arrays.toString(new Solution().twoSum(new int[] { 2, 7, 11, 15 }, 9)));
}
}
Python
'''
@Author: Goog Tech
@Date: 2020-07-13 21:49:08
@Description: #1. Two Sum
@FilePath: \leetcode-googtech\#1. Two Sum\Solution.py
'''
class Solution:
''' 暴力法 '''
def twoSum(self, nums, target):
n = len(nums)
for x in range(n):
for y in range(x + 1, n):
if (nums[x] + nums[y] == target):
return x, y
break
else:
continue
''' 测试 '''
print(Solution().twoSum([2, 7, 11, 15], 9))