Wednesday, August 29, 2018

Leetcode 1: Two sum - Love keeps no record of wrongs

August 29, 2018

Introduction


It is so surprising that I had chance to review the code I wrote more than three years ago. Here is the link.

I like to write a blog about the algorithm, and I like to highlight what I have learned based on the code I wrote in 2015.

Review line by line 


Here is the C# code I wrote in 2015.

At that time, I did not experience code review on stackexchange.com, I can get free advice on my algorithms. Also I did not have enough wisdom to pick up good crafting skills.

I did not master C# programming language very well after working full time five years, day in and day out using C# to do software programmer job.

I was shy and I did not write any coding blog as a daily habit, and I did not express myself so often.

I did not talk to over 300 software programmer and help each other to prepare for the interviews. Even though I meet people at meetup for software industry, but no one talked to me about coding and crafting.

In summary, back to 2015, it is like ancient history for me. I just know that I was happy and younger.


/*
* source code from blog:
* http://www.acmerblog.com/leetcode-two-sum-5223.html
*
* 解法1:先排序,然后从开头和结尾同时向中间查找,原理也比较简单。复杂度O(nlogn)
*
* julia's comment:
*
*/
public static ArrayList twoSum(int[] numbers, int target)
{
int len = numbers.Length;
Node[] tmpNodes = new Node[len];
for (int i = 0; i < len; i++)
{
tmpNodes[i].id = i + 1;
tmpNodes[i].val = numbers[i];
}
Node[] nodes = sortArray(tmpNodes);
int start = 0, end = len - 1;
ArrayList ans = new ArrayList();
while (start < end)
{
if (nodes[start].val + nodes[end].val == target)
{
if (nodes[start].id > nodes[end].id)
{
swap(ref tmpNodes, start, end);
ans.Add(tmpNodes[start].id);
ans.Add(tmpNodes[end].id);
return ans;
}
else if (tmpNodes[start].val + tmpNodes[end].val < target)
start++;
else
end--;
}
}
return ans;
}
public static void swap(ref Node[] nA, int start, int end)
{
Node tmp = nA[start];
nA[start] = nA[end];
nA[end] = tmp;
}
public static Node[] sortArray(Node[] nA)
{
return nA; // implement later
}
public static bool compare(Node a, Node b){
return a.val < b.val;
}
I like to talk about code smells, crafting skills, Array.Sort and all other things one by one later.

No comments:

Post a Comment