Two Sum
js
var twoSum = function(nums, target) {
let emptyArray = []
for (let i = 0; i < nums.length; i++) {
if (emptyArray.indexOf(nums[i]) === -1) {
emptyArray[i] = target - nums[i]
} else {
return [emptyArray.indexOf(nums[i]), i]
}
}
js解题思路:
- 声明空数组emptyArray
- 使用for循环遍历nums
- if语句判断,如果元素在声明的空数组不存在,则储存与之和为9的数进去,如果存在则返回一个数组
java
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] emptyArray = new int[]{0,0};
if (nums == null || nums.length < 2) {
return nums;
}
HashMap<Integer,Integer> hashmapArray = new HashMap<Integer,Integer>();
for (int i = 0; i <nums.length; i++) {
if (hashmapArray.containsKey(nums[i])){
return new int[]{hashmapArray.get(nums[i]),i};
} else {
hashmapArray.put(target-nums[i],i);
}
}
return nums;
}
}
java解题思路:
- new一个数组emptyArray出来
- 判断参数数组如果为空或者长度小于2则直接返回原数组
- 创建一个新的hashmap散列表hashmapArray 出来
- for循环参数数组
- 判断如果当前键名存在则在array中返回当前键值和循环次数
- 如果找不到相加为target的,则返回原数组
js 收获
Array.prototype.indexOf
语法: arr.indexOf(searchElement, fromIndex)
searchElement: 必需,需要检索的字符串
fromIndex: 非必需,检索开始的位置
java 收获
HashMap
根据key获取value: get(key)
存储键值对: put(key, value)
查询键值是否存在: containsKey(key)