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].
answer:
myCode:
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=0;j<nums.length;j++){
if(nums[i]+nums[j]==target){
return new int[]{i,j};
}
}
}
return null;
}
}
lear from this test:
1.數據初始化的兩種方式:
Java語言中數組必須先初始化,然後纔可以使用。所謂初始化就是爲數組的數組元素分配內存空間,併爲每個數組元素附初始值。
注意:數組完成初始化後,內存空間中針對該數組的各個元素就有個一個默認值:
基本數據類型的整數類型(byte、short、int、long)默認值是0;
基本數據類型的浮點類型(float、double)默認值是0.0;
基本數據類型的字符類型(char)默認值是'\u0000';
基本數據類型的布爾類型(boolean)默認值是false;
類型的引用類型(類、數組、接口、String)默認值是null.
1.靜態初始化
int[] intArr;
intArr = new int[]{1,2,3,4,5,9};
2.簡化的靜態初始化方式 type[] arrayName = {element1,element2,element3...};
String[] strArr = {"張三","李四","王二麻"};
3.動態初始化:初始化時由程序員指定數組的長度,由系統初始化每個數組元素的默認值。
arrayName = new type[length];
示例:
int[] price = new int[4];