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.
publicclassSolution {publicint[] twoSum(int[] numbers, int target) {
String source = numbers.toString();
int[] result = newint[2];
//int l = numbers.size();
l = source.length();
int i, j;
for (i = 0; i < l; i++){
for(int j = i + 1; j < l; j++){
if(numbers[i] + numbers[j] = target){
result[0] = i;
result[1] = j;
return result;
}
}
}
}
}
Result:
Line 6: error: cannot find symbol: variable l
这个错误就是粗心大意了, 后面还有一个错误:
Line 9: error: variable j is already defined in method twoSum(int[],int)
我还是再看一遍code再提交吧
审查了一遍,又发现个错误, i的边界判定不应该是length, 而应该是length - 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
publicclassSolution {publicint[] twoSum(int[] numbers, int target) {
String source = numbers.toString();
int[] result = newint[2];
int l = source.length();
int i, j;
for (i = 0; i < l - 1; i++){
for(j = i + 1; j < l; j++){
if(numbers[i] + numbers[j] = target){
result[0] = i;
result[1] = j;
return result;
}
}
}
}
}
Arrays are special objects in java, they have a simple attribute named length which is final.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.Note also that ArrayList.size() provides the number of object actually stored in the array whereas myArray.length ([]) provides the "capacity". That is, if for myArray = new int[10];, it returns 10. It is not the number of objects you've put in the array.