Java实现LeetCode_0001_Two Sum
程序员文章站
2024-02-19 15:13:40
...
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
上一篇: my sql 数据库迁移,只迁移指定条件的数据,如何实现?求!
下一篇: PHP-继承-笔记