题目:
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].

来源:leetcode

分析:
题目大意:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

解答:直接暴力,无话可说

public int[] twosum(int[] arr,int target){
   
	for(int i=0;i<arr.length;i++){
   
		for(int j=i+1;j<arr.length;j++){
   
		if(arr[i]+arr[j] == target)
			return new int[]{
   i,j};
			}
		}
		throw new IllegalArgumentException("No two sum solution");
	}

解法(与一相同,不同的输出形式而已):

 for (int i = 0; i <nums.length ; i++) {
   
            for (int j = i+1; j <nums.length ; j++) {
   
                if (nums[i]+nums[j]==target){
   
                    a=i;
                    b=j;
                }
            }

        }
        System.out.println('['+a+','+b+']');
    }

tips:所有代码段均是在idea编译器测试通过!