Leet Code 1:计算数组中两个任意数加起来等于目标数

Two sum (leetcode)

refer:https://oj.leetcode.com/problems/two-sum/

Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

数组中任意两项加起来等于给定的目标数,求出数组中两个数的下标,下标从1开始。

java 代码实现:

public class Solution {
   //给定一个数组,数组里面下标加起来等于 给定的目标数字,求下标
   public static void main(String[] args) {
   Solution solution=new Solution();
   int[] number={1,2,7,11};
   solution.twoSum(number,18);
   }
   public int[] twoSum(int[] numbers, int target) {
	int num[]=new int[2];
	for(int i=0;i<numbers.length;i++){
		for(int k=i+1;k<numbers.length;k++){
			if(numbers[i]+numbers[k]==target){
				num[0]=i+1;
				num[1]=1+k;
                                    System.out.println(i+1+"---"+(k+1));
			}
		}
	}
	
	return num;
}
}

输出结果为 3,4

小球轨迹
原文地址:https://www.cnblogs.com/importnew/p/4230415.html