该题目和两数之和差不多。
给定一个数组,给定一个数,如果数组中存在两个元素相乘等于给定的数,则返回这两个数字的数组下标,存在多个结果的话随意返回一个即可,若不存在则返回-1,-1。
当时用两个for循环遍历解决的,时间复杂度:O(N2),很明显超时了,用例通过20%。现用哈希表再做一遍。哈希表只需要一次遍历,时间复杂度O(N)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer ,Integer> hashtable = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
if(hashtable.containsKey(target / nums[i])){
return new int[]{hashtable.get(target / nums[i]),i};
}
hashtable.put(nums[i],i);
}
return new int[] {-1,-1};
}
}