时间: 2019-10-08 11:21 PM
题目地址: https://leetcode.com/problems/two-sum/
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
给定一个整型数组,以数组的形式返回相加等于指定数值的元素索引。元素不可被使用两次。
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Solution:
class Solution {
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
}