第一题,Two Sum
此题给定一个数组和目标target,求两个数之和等于target,返回这两个数的下标位置
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6 Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6 Output: [0,1]
经典解法就是双循环数组,遇到相等的直接返回即可(无重复答案)
public int[] twoSum(int[] nums, int target) { int len = nums.length; for(int i = 0; i < len; i ++) for(int j = i+ 1; j < len; j++) { if (nums[i] + nums[j] == target) return new int[]{i,j}; } return new int[]{-1,-1}; }
需要注意的点
1、j从i+1开始,不要再从1开始循环了
2、直接返回new int[]{i,j},这种方式可以学习一下,作为java生成数组的一种方式