public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] arr = 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){
arr[0] = i;
arr[1] = j;
return arr;
}
}
}
return arr;
}
}
一个普通的遍历算法,时间为$O(n^2)$,速度较慢。 如果使用hashmap的方式可以使速度变快,只需要$O(n)$就可以完成 代码如下:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];
HashMap<Integer, Integer> hm = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int another = target - nums[i];
if(hm.containsKey(another)){
arr[0] = hm.get(another);
arr[1] = i;
return arr;
}
hm.put(nums[i], i);
}
return arr;
}
}
python 方法,利用dict
class Solution(object):
def majorityElement(self, nums):
judge = 0.5
num_dict={}
for i in range(len(nums)):
if nums[i] in num_dict:
num_dict[nums[i]] = num_dict[nums[i]] + 1
else:
num_dict[nums[i]] = 1
for num, counts in num_dict.items():
if counts*1.0/len(nums) > judge:
return num