A, the title
Given an array of integers nums and a target value target, find the two integers in the array and the target values and return their array subscripts. 【 Force link 】
You can assume that there is only one answer for each type of input. However, you cannot reuse the same elements in this array.
Second, the sample
Given nums = [2, 7, 11, 15], target = 9Copy the code
Three, the analysis
This [sum of two numbers] force buckle on the difficulty of the first problem is also simple, is a relatively simple problem. Just find the sum of two numbers in the array equal to the target value and return the array subscript, that is, each number is added to the other numbers once.
Four, implementation,
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j ++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j; }}}returnresult; }}Copy the code
[I +1, nums.length – 1]; [j +1, nums.length]; [j +1, nums.length]; [j +1, nums.length]; So j takes the value I +1 up to the array size, and then returns the nested traversal comparison