标签:
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.
标签:
原文地址:http://www.cnblogs.com/suncosmo/p/4731416.html