码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode_Algotithms_TwoSum

时间:2015-08-15 00:01:30      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:

leetCode problems of Algotithms

从今天开始尝试用纯英文写随笔,当是锻炼自己的英语水平吧。希望自己以后能看懂~

Because I don‘t know that if the leetCode.com has any disagreements about sharing their questions in other websites, so there would be no further details about the problem. The index of this question "Two Sum" is 1 which belongs to the title of "Algotithms" in leetCode.

This is my first solution in Java, it‘s be solved in a pretty stupid way...

public class solution {
    public static int[] twoSum(int[] nums, int target) {
        int result[] = new int[2];
        for(int m=0; m<nums.length; m++){
            //int defNum = target - nums[m];
            for(int n= m+1; n<nums.length; n++){
                if(nums[m]+nums[n] == defNum){
                    result[0] = ++m;
                    result[1] = ++n;
                    break;
                }
            }
        }
        return result;
    }
}

Looking carefully you can find out that I used a unnecessary addition in the process of second loop. In fact I can do the operation before the loop so that in second loop we can just compare the two numbers to find out the result.

public class solution {
    public static int[] twoSum(int[] nums, int target) {
        int result[] = new int[2];
        for(int m=0; m<nums.length; m++){
            int defNum = target - nums[m];
            for(int n= m+1; n<nums.length; n++){
                if(nums[n] == defNum){
                    result[0] = ++m;
                    result[1] = ++n;
                    break;
                }
            }
        }
        return result;
    }
}

Now it‘s better, however the whole thinking to solve this problem of mine is still like crap. I use the loop twice to ergodic(遍历) the array so I can find what I want, it costs space and time. In fact, if I‘m clever enough, I‘ll nerver stay here and tying to be a real programmer. 

The big guy in leetCode solve this problem in a different way, to fingue out their throught I have to review the conception of List、Set and Map in Java. Because I have to go to the fucking sweat shop tomorrow, Today‘s blog would be done here temporary.

 

leetCode_Algotithms_TwoSum

标签:

原文地址:http://www.cnblogs.com/suncosmo/p/4731416.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!