算法练习:入门系列Two Sum

从最简单的easy 模式开始。

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Accepted  1,973,764  Submissions  4,450,090

最简单系列:通过率也就是不到1/2吧

数组嘛,最直接想到的就是循环。双重循环。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        
        int[] result = new int[2];
        for(int i=0;i< nums.length-1;i++ ){                   
                result[0] =i;            
            for(int j=i+1;j<nums.length;j++ ){
               
                	 result[1] = j;
                    if(nums[i]+nums[j] == target){
                    	
                        return result;
                    }
                
            }
            
        }
		return result;
    }
}

找不到应该打印依据或者抛个异常。测试 通过

Runtime: 31 ms

Memory Usage: 36.8 MB

缺点:太慢, 优点:节省内存。

Complexity Analysis

  • Time complexity : O(n^2)O(n2). For each element, we try to find its complement by looping through the rest of array which takes O(n)O(n) time. Therefore, the time complexity is O(n^2)O(n2).

  • Space complexity : O(1)O(1). 

改进法:争取降到O(n)

  引入hashmap做判断,

class Solution {
    public int[] twoSum(int[] nums, int target) {
          Map<Integer,Integer> map = new HashMap();
    int[] result = new int[2];
    for(int i=0;i< nums.length-1;i++ ){ 
        map.put(nums[i],i);
    }    
                       
    for(int j=1;j<nums.length;j++ ){               
            result[1] = j;
            int tmp = target- nums[j];
        if(map.containsKey(tmp) &&  map.get(tmp) != j){
             result[0] = map.get(tmp);      	
            return result;
        }            
    }
	return result;
    }
}

Runtime: 2 ms

Memory Usage: 37.4 MB

比之前快多了,内存有一点增加。

Complexity Analysis:

  • Time complexity : O(n)O(n). We traverse the list containing nn elements exactly twice. Since the hash table reduces the look up time to O(1)O(1), the time complexity is O(n)O(n).

  • Space complexity : O(n)O(n). The extra space required depends on the number of items stored in the hash table, which stores exactly nn elements. 

还有更好的方法,。。。。。

习惯了开发工具,直接写代码真不适应。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值