LeetCode : two sum
第一次写博客,算是熟悉这些编辑环境吧,本来是打算在csdn上用markdown写的,结果改了博客介绍就被关闭了,晕死。。。好了,话不多说,今天打算拿LeetCode上的第一题:Two Sum来分享试验一下。
题目描述: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.
例子:Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
分析:看到题目之后了解到需求为找到数组中两个数之和满足给定target的下标,保存在一个数组中返回。一个简单的思路就是像冒泡排序一样利用两层遍历来
找到结果。复杂度为o(n^2).
1 public int[] twoSum(int[] nums, int target) { 2 int [] result=new int [2]; 3 for(int i=0;i<nums.length;i++){ 4 for(int j=i+1;j<nums.length;j++){ 5 if((nums[i]+nums[j])==target){ //遍历数组,找到满足的两个数的下标保存在数组中 6 result[0]= nums[i]; 7 result[1]= nums[j]; 8 } 9 } 10 } 11 if(result[0]==result[1]&&result[0]==0){ //这一步很多人不会注意,要判断原来初始化的数组中的数是否满足都不为0的要求 12 return null; 13 }else{ 14 return result; 15 } 16 17 }
其实这道题是一年前写的了,当时也就是为了通过而通过,所以没管复杂度的问题,其实这不是一个好习惯,今天第一次写博客又想了下,找到了更好的方法,利用
hashmap可以实现o(n):
1 public static int[] twosum(int[] num,int target){ 2 HashMap<Integer,Integer> map = new HashMap<>(); //构建hashmap 3 for (int i = 0;i<num.length;i++){ 4 if (map.containsKey(target-num[i])){ //判断当前map中有木有与num[i]和为target的键,如果有则找到这对键值, 5 return new int[]{map.get(target-num[i]),i+1}; // 和当前下标组成结果 6 }else { 7 map.put(num[i],i); 8 } 9 } 10 return null; 11 }
那么现在就算是完成这道题了吧,发现写博客真的不是一件那么简单的事,希望能坚持下来吧,最后来一张我gakki的美照纪念一下

浙公网安备 33010602011771号