LeetCode1_Two Sum

My answer

第三遍提交

<span style="font-weight: bold;">   </span> /**
     * running time : O(n)
     */
    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        
        int size = numbers.length;
        for(int i=0; i<size; i++){
            int curr = numbers[i]; 
            if(!map.containsKey(curr)){
                map.put(target - curr, i);
            }else{
                result[0] = map.get(curr) + 1;
                result[1] = i+1;
               break;
            }
        }
        
       return result; 
    }
第一遍提交

<strong>  </strong> /**
     * running time is O(n^2)
     * 返回结果 Time Limit Exceeded
     * LeetCode使用的测试用例,是超长的数组
     * Last executed input: [0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,....]
     * 
     * 教训: 程序不能只是正确性,还要考虑效率。
     */
    public int[] twoSumVersion1(int[] numbers, int target) {
        int[] result = new int[2];
        
        for(int i=0; i<numbers.length; i++){
            int rightOperand = target - numbers[i];

            for(int j=i+1; j<numbers.length; j++){
                if(rightOperand == numbers[j]){
//                    Please note that your returned answers (both index1 and index2) are not zero-based.
                    result[0] = i+1;
                    result[1] = j+1;
                    return result;
                }
            }
        }
        return result;
    }

Summary

1.     1st answer is O(n^2)

      The two-layer loops algorithm is first idea for most people. However, the running time is O(n^2), which means it might be not be used in real application.

2.     2nd answer based on Hash Map; store all elements on Hash Map.

      Disadvantage: This algorithm needs a very big space to store elements in hash map. Most of elements are not the output concerns.

3.     3rd answer based on Hash Map; only store the examined elements on Hash Map.

     3.1   the output order is not a matter

     3.2   For-loop keeps one output. 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值