LeetCode的第一题
Two Sum
Total Accepted: 309644
Total Submissions: 1145736
Difficulty: Easy
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
给的解释太少,又因为是第一次在这做题,闹了一些笑话。
看完题后,想着用最笨的办法,很简单,自己写main函数,用上给的接口。但对于题目给的输入没搞明白,以为是字符串,需要自己将数字提取转换为整数数组,最后还要把结果再转换为字符串输出。才学java,对于字符串转化啥的也不是很了解。上网查了半天终于弄好了,提交却怎么也不正确。百度了一下LeetCode的检测原理才知道,只需要把接口写好就行,根本不要什么字符串转换。咳咳咳。。。
字符串转换版的(比较渣):
package test_1;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
/*public int[] twoSum(int[] nums, int target) {
for (int i=0; i<nums.length-1; i++){
for (int j=i+1; j<nums.length; j++){
if (nums[i]+nums[j] == target){
int[] b = {i,j};
return b;
}
}
}
return null;
}*/
public int[] twoSum(String nums, int target) {
int[] a = new int[nums.length()];
for (int i=0; i<nums.length(); i++){
a[i] = nums.charAt(i)-'0';
}
//System.out.println(a[0]);
for (int i=0; i<a.length-1; i++){
for (int j=i+1; j<a.length; j++){
if (a[i]+a[j] == target){
int[] b = {i,j};
return b;
}
}
}
return null;
}
public static void main(String[] args){
Test s = new Test();
Scanner in = new Scanner(System.in);
String array = in.next();
int target = in.nextInt();
//int[] a = new int[array.length()/2];
String a = new String();
//System.out.println(array);
for (int i=0; i<array.length(); i++){
if (array.charAt(i) <= '9' && array.charAt(i)>='0'){
a += array.charAt(i);
}
}
System.out.println(
Arrays.toString(s.twoSum(new String(a), target)));
}
}
最终提交结果:
“`
public class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i=0; i