1.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].
思路:数组中两个整数相加,可以通过循环实现,如果要达到逐个相加就需要双重循环。还需要考虑到的一点是重复的两个数字索引不同,这也是一种情况。
public class Solution { public int[] twoSum(int[] nums, int target) { int sum = 0; int[] ints = new int[2]; for(int i = 0;i < nums.length;i++){ for (int j=i+1;j<nums.length;j++){ sum=nums[i]+nums[j]; if (sum==target){ ints[0]=i; ints[1]=j; return ints; } } } return ints; } }
以上是第一次没考虑到重复的情况。