LeetCode1:
給定一個整數數組 nums 和一個目標值 target,在該數組中找出和為目標值的那 兩個 整數,並返回他們的數組下標。
可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。
示例 1:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解法一:
兩個for循環遍歷:
class Solution {
public int[] twoSum(int[] nums, int target) {
int res[] = new int[2];
for(int i = 0; i < nums.length; i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
res[0] = i;
res[1] = j;
break;
}
}
}
return res;
}
}
解法二:
使用Hash表:
class Solution {
public int[] twoSum(int[] nums, int target) {
int res[] = new int[2];
Map<Integer, Integer> map= new HashMap<>();
for(int i = 0; i < nums.length; i++){
map.put(nums[i], i);
}
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp) && map.get(temp) != i){
res[0] = map.get(temp);
res[1] = i;
}
}
return res;
}
}
知識點:
主要hashmap方法的使用:
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//(key, value)
HashMap<String, Integer> map = new HashMap<String, Integer>();
//向map中添加值
map.put("jiang", 1);
map.put("wen", 2);
System.out.println(map);
//取值(得到map中,key對應的value)
int temp = map.get("jiang");
System.out.println(temp);
//判斷map是否為空
System.out.println(map.isEmpty());
//判斷是否含有key
System.out.println(map.containsKey("jiang"));
//判斷是否含有value
System.out.println(map.containsValue(1));
//刪除key對應的value
map.remove("jiang");
System.out.println(map.get("jiang"));
//顯示所有map的value值
System.out.println(map.values());
//元素個數
System.out.println(map.size());
}
}
