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];