Blog Archive

Tuesday, September 30, 2014

[Leetcode] Longest Valid Parentheses @Python - Sumnous's Blog

[Leetcode] Longest Valid Parentheses @Python - Sumnous's Blog: " if s == '' or s == '(' or s == ')':
return 0
stack = [(-1, ')')]
maxLen = 0
for i in xrange(len(s)):
if s[i] == ')' and stack[-1][1] == '(':
stack.pop()
maxLen = max(maxLen, i - stack[-1][0])
else:
stack.append((i, s[i]))
return maxLen"



'via Blog this'

Monday, September 29, 2014

霸气侧漏的在读博士

George E. Dahl: "George E. Dahl"





Currently, I am not on the job market. However, I expect to finish my Ph.D. this year. If you want to be notified when I start making post-graduation career plans and we haven't already spoken, please send me an email.



http://www.cs.toronto.edu/~gdahl/



[No offense, I just wish I can have the feeling of being a King like this guy]

'via Blog this'

Programming Interview Questions

Programming Interview Questions:



'via Blog this'

Saturday, September 27, 2014

temp

http://www.cnblogs.com/zuoyuan/p/3700105.html
http://www.cnblogs.com/zzzdevil/p/3648348.html
http://www.cnblogs.com/zuoyuan/p/3703075.html

Monday, September 15, 2014

LeetCode题解整理版(二) | Coding 4 Fun

LeetCode题解整理版(二) | Coding 4 Fun: " i = len(s) - 1
while i >= 0 and s[i] == ' ': i -= 1
j = i - 1
while j >= 0 and s[j] != ' ': j -= 1
return 0 if i < 0 else i - j"



'via Blog this'

[leetcode]Simplify Path @ Python - 南郭子綦 - 博客园

[leetcode]Simplify Path @ Python - 南郭子綦 - 博客园:



'via Blog this'

[leetcode]Implement strStr() @ Python - 南郭子綦 - 博客园

[leetcode]Implement strStr() @ Python - 南郭子綦 - 博客园: " if len(haystack) < len(needle): return None
i = 0
while i < len(haystack)-len(needle)+1:
j = 0; k = i
while j < len(needle):
if haystack[k] == needle[j]:
j+=1; k+=1
else:
break
if j == len(needle):
break
else:
i+=1
if i == len(haystack)-len(needle)+1:
return None
else:
return haystack[i:]"



'via Blog this'

[leetcode]Valid Palindrome @ Python - 南郭子綦 - 博客园

[leetcode]Valid Palindrome @ Python - 南郭子綦 - 博客园: " if s == '':
return True
else:
sTmp = ''
for i in range(0, len(s)):
if s[i] >= 'a' and s[i] <= 'z' or s[i] >= '0' and s[i] <= '9' or s[i] >= 'A' and s[i] <= 'Z':
sTmp += s[i]
sTmp = sTmp.lower()
for i in range(0, len(sTmp)/2):
if sTmp[i] != sTmp[len(sTmp)-1-i]:
return False
return True"



'via Blog this'

Sunday, September 14, 2014

[leetcode]Copy List with Random Pointer @ Python - 南郭子綦 - 博客园

[leetcode]Copy List with Random Pointer @ Python - 南郭子綦 - 博客园: "if head == None: return None
tmp = head
while tmp:
newNode = RandomListNode(tmp.label)
newNode.next = tmp.next
tmp.next = newNode
tmp = tmp.next.next
tmp = head
while tmp:
if tmp.random:
tmp.next.random = tmp.random.next
tmp = tmp.next.next
newhead = head.next
pold = head
pnew = newhead
while pnew.next:
pold.next = pnew.next
pold = pold.next
pnew.next = pold.next
pnew = pnew.next
pold.next = None
pnew.next = None
return newhead"



'via Blog this'

[leetcode]Swap Nodes in Pairs @ Python - 南郭子綦 - 博客园

原题地址:http://oj.leetcode.com/problems/swap-nodes-in-pairs/
题意:将链表中的节点两两交换。Given 1->2->3->4, you should return the list as 2->1->4->3.
解题思路:这题主要涉及到链表的操作,没什么特别的技巧,注意不要出错就好。最好加一个头结点,操作起来会很方便。
代码:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self, head):
        if head == None or head.next == None:
            return head
        dummy = ListNode(0); dummy.next = head
        p = dummy
        while p.next and p.next.next:
            tmp = p.next.next
            p.next.next = tmp.next
            tmp.next = p.next
            p.next = tmp
            p = p.next.next
        return dummy.next
        



Saturday, September 13, 2014

[leetcode]Remove Nth Node From End of List @ Python - 南郭子綦 - 博客园

[leetcode]Remove Nth Node From End of List @ Python - 南郭子綦 - 博客园: " dummy=ListNode(0); dummy.next=head
p1=p2=dummy
for i in range(n): p1=p1.next
while p1.next:
p1=p1.next; p2=p2.next
p2.next=p2.next.next
return dummy.next"



'via Blog this'

[leetcode]Add Two Numbers @ Python - 南郭子綦 - 博客园

[leetcode]Add Two Numbers @ Python - 南郭子綦 - 博客园:



'via Blog this'

[leetcode]Rotate List @ Python - 南郭子綦 - 博客园

[leetcode]Rotate List @ Python - 南郭子綦 - 博客园: " if k == 0:
return head
if head == None:
return head
dummy = ListNode(0)
dummy.next = head
p = dummy
count = 0
while p.next:
p = p.next
count += 1
p.next = dummy.next
step = count - ( k % count )
for i in range(0, step):
p = p.next
head = p.next
p.next = None
return head"



'via Blog this'

[leetcode]Plus One @ Python - 南郭子綦 - 博客园

[leetcode]Plus One @ Python - 南郭子綦 - 博客园: "class Solution:
# @param digits, a list of integer digits
# @return a list of integer digits
def plusOne(self, digits):
flag = 1
for i in range(len(digits)-1, -1, -1):
if digits[i] + flag == 10:
digits[i] = 0
flag = 1
else:
digits[i] = digits[i] + flag
flag = 0

if flag == 1:
digits.insert(0, 1)
return digits"



'via Blog this'

Friday, September 12, 2014

[leetcode]Valid Sudoku @ Python - 南郭子綦 - 博客园

[leetcode]Valid Sudoku @ Python - 南郭子綦 - 博客园:



'via Blog this'

How to Read Linux Top Command Output and Uses - TecAdmin.net

How to Read Linux Top Command Output and Uses - TecAdmin.net: "Using this article, I am trying to write to how to use and read results of top command."



'via Blog this'

[leetcode]Valid Sudoku @ Python - 南郭子綦 - 博客园

[leetcode]Valid Sudoku @ Python - 南郭子綦 - 博客园:



'via Blog this'

Dropped iphone 5 in water. Help? | Apple Support Communities

Dropped iphone 5 in water. Help? | Apple Support Communities: "I used the bag of rice method this weekend and it worked.  My iphone 5 had been in my pocket when I fell in our pool while cleaning the pool. So the phone was fully submerged for about 3-4 seconds. I could see water in the camera lens after this occured. It was definitely wet.
 
First I sucked the water out of the speaker holes with my mouth. Then I turned off the phone. Researched online and found the rice method. I put the phone in a ziplock bag with brown rice (it was all we had) about 45 minutes after the incident. A little while later I was able to find some silica gel packets in some vitamin bottles so I put those in the bag of rice with the phone (another technique found online).
 
The phone was in there from around 3:30 PM Saturday afternoon until 9:30 AM Monday morning. Took it out this morning and tried to turn it on but wouldn't - got the red low battery signal. After 10 minutes of charging it booted up on it's own. Works fine now. Hopefully it stays that way. By the way check your charger connector on the phone for rice. Luckily I looked before plugging it in. I tapped it on the desk and dislodged 3 pieces of rice that would have been smashed in there had I not checked first."



'via Blog this'

[leetcode]Permutation Sequence @ Python - 南郭子綦 - 博客园

[leetcode]Permutation Sequence @ Python - 南郭子綦 - 博客园: " res = ''
k -= 1
fac = 1
for i in range(1, n): fac *= i
num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in reversed(range(n)):
curr = num[k/fac]
res += str(curr)
num.remove(curr)
if i !=0:
k %= fac
fac /= i
return res"



'via Blog this'

Monday, September 8, 2014

C++11 improvements over C++03

Source:
http://www.cplusplus.com/articles/EzywvCM9/

About C++11

C++11 aka C++0x is the new standard of the C++ language, published in late 2011.
It supersedes the older C++03 standard, which was published in 2003.
Naturally, it brings improvements over the old standard, some of which this article will outline.

The revamped auto keyword

Verbosity is bad, mainly because it makes your code less clear.
So the auto keyword, a leftover from C, got a new meaning in C++11: automatic type deduction.

Example:
1
2
3
4
5
6
// the C++03 way
for (std::vector<int>::const_iterator ci = v.begin(); ci != v.end(); ++ci);

// the C++11 way
for (auto ci = v.cbegin(); ci != v.cend(); ++ci);
// notice the dedicated cbegin() and cend() member functions which return a const_iterator 



Bad example:
1
2
3
4
5
6
7
8
9
10
auto x = 10.0;
// if a newbie programmer changes `10.0' to `10', x becomes an integral type
// and code depending on it to be a floating point type will fail
// advice 1: use auto against verbosity, not consistency

for (auto i = 0ul; i < v.size(); ++i);
// this is just a clever way of writing `unsigned long int i=0'
// advice 2: don't use auto if you specify the type, it defeats its purpose

// advice 1+2=3: don't use auto with constants 



Range-based for()

Iterating over the contents of STL containers is a very common operation.
C++11 now provides a specialized for() which can iterate over anything that has a begin() and an end() member function, which return the expected iterators.
It also works on plain C arrays.

Example:
1
2
3
4
5
6
7
8
9
10
// the C++03 way
for (std::vector<int>::iterator i = v.begin(); i != v.end(); ++i);

// the C++11 way
for (int &item: v);
// item will become, in order, all the things stored in v
// notice how we're referencing the item, that allows us to change it

for (const int &item: v); // can't change item, we reference it for speed
for (int item: v); // can't change item, we're passing it by value 



Initializer lists

The containers in C++03 could not be initialized as "naturally" as good old C-style arrays. That has changed.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// C arrays
char   array1[] = {'A', 'B'};
double array2[] = {32.0, 6.003, -0.1};

// C++03 vectors

std::vector<char> cpp03vector1;
cpp03vector1.push_back('A');
cpp03vector1.push_back('B');

std::vector<double> cpp03vector2(3);
cpp03vector2[0] = 32.0;
cpp03vector2[1] = 6.003;
cpp03vector2[2] = -0.1;

// C++11 vectors
std::vector<char>   cpp11vector1 = {'A', 'B'};
std::vector<double> cpp11vector2 = {32.0, 6.003, -0.1};
// or...
std::vector<char>   cpp11vector3{'A', 'B'};
std::vector<double> cpp11vector4{32.0, 6.003, -0.1};
// notice that this works for all other containers as well, not just std::vector 



Initializer lists can also be used for more complex structures.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <map>
#include <string>
#include <vector>
#include <utility>

using namespace std;

map<string, vector<pair<string, int>>> name_languages_year {
    {"Dennis Ritchie",    {{"B",      1969}, {"C",        1973}}},
    {"Niklaus Wirth",     {{"Pascal", 1970}, {"Modula-2", 1973}, {"Oberon", 1986}}},
    {"Bjarne Stroustrup", {{"C++",    1983}}},
    {"Walter Bright",     {{"D",      1999}}}
};
// notice how the lists are nested to match the templates' parameters

cout << name_languages_year["Niklaus Wirth"].at(0).first << endl; // prints `Pascal'

// adds a new entry to the map
name_languages_year["John McCarthy"] = {
    {"Lisp", 1958}
};
// notice the lack of explicit types 



C++ arrays


This is more of an addition than an improvement, but I decided to include it in the article anyway.
C++11 provides std::array, which has the purpose of replacing C arrays. It is a fixed-sized, lightweight alternative to the dynamically-sized std::vector.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <array>

// C arrays
char  carray1[] = "Abc"; // caution, an unseen '\0' is added to the end
float carray2[] = {0.2f, 33.33f};

// C++ arrays
std::array<char, 3>  cpparray1{{'A', 'b', 'c'}};
std::array<float, 2> cpparray2{{0.2f, 33.33f}};
// observation 1: the size must be deducible at compile time
// observation 2: the array cannot be resized
// observation 3: the inner braces are due to the nature of initializer lists,
//  think of it as one list per template parameter

// array test drive: the old versus the new

std::cout << sizeof carray1 - 1; // -1 because of the extra '\0'
std::cout << sizeof carray2 / sizeof (float); // because number of elements != number of bytes
std::cout << cpparray1.size();
std::cout << cpparray2.size();

carray2[-5] = 0.1f; // do the moonwalk!
cpparray2.at(-5) = 0.1f; // throws std::out_of_range exception

// of course there are more reasons why C++ arrays are better than C arrays
// but this example code section is already too big... 



Minor fixes

C++03 had a bunch of minor glitches and design flaws which were fixed in C++11:
  • Things like set<vector<int>> finally compile.
    Notice the lack of space between the last two angle brackets.

  • std::string now has front() and back() member functions.

  • File streams now accept an std::string as filename.
    This means one less use for the ridiculous c_str() member function.

  • Easy conversion of numerical values to std::string is now possible through the use of the overloaded functions:
    string to_string(int)
    string to_string(float)
    string to_string(double)
    ...

Compiler support for C++11

... is not too bad. But give it a year or two to set.

The GNU C++ compiler requires the commandline parameter -std=c++0x to compile C++11 code.

Microsoft Visual Studio 2010 has partial support for C++11 features, out of the box.
Microsoft Visual Studio 201x (v11) will still only have partial support for C++11 features.

K-means算法及k-means++、SVD的优化 - 推酷

K-means算法及k-means++、SVD的优化 - 推酷:



'via Blog this'

Wednesday, September 3, 2014

c++ - Compiling C++11 with g++

http://stackoverflow.com/questions/10363646/compiling-c11-with-g

Flags (or compiler options) are nothing but ordinary command line arguments passed to the compiler executable.
Assuming you are invoking g++ from the command line (terminal):
$ g++ -std=c++11 your_file.cpp -o your_program
or
$ g++ -std=c++0x your_file.cpp -o your_program
if the above doesn't work.