Java实现LeetCode_0001_Two Sum

import java.util.Arrays;
import java.util.Scanner;

public class TwoSum_1 {
	public static void main(String[] args) {
			@SuppressWarnings({ "resource"})
			Scanner input = new Scanner(System.in);
			System.out.println("Please input the array's length:");			
			int length=input.nextInt();
			int []nums=new int[length];
			System.out.println("Please input the array elements:");
			for(int i=0;i<nums.length;i++) {
					nums[i]=input.nextInt();
			}//end for
			System.out.println("Please input the target:");
			int target=input.nextInt();
			System.out.println(Arrays.toString(twoSum(nums,target)));
	}// end main()

/**
 *
 *the function of judge 
 *@param
 *	
 * */
	public static int[] twoSum(int[] nums, int target) {
		int i, j; // index
		for (i = 0; i < nums.length; i++) {
			for (j = i+1; j < nums.length; j++) {
				if (target - nums[j] == nums[i]) {
					return new int[] {i,j};
				} // end if
			} // end for
		} // end for
		 throw new IllegalArgumentException("No two sum solution");
	}// end twoSum()

}// end TwoSum_1


posted @ 2019-07-30 21:20  南墙1  阅读(65)  评论(0编辑  收藏  举报