Wednesday, June 5, 2013

Rotate List@leetcode

微博:http://www.weibo.com/cathyhwzn

刷题必备书籍:Cracking the Coding Interview: 150 Programming Questions and Solutions
Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

Few points here:
1. To notice that no matter how many elements to rotate, the order of the list won't change. So we can connect them as a circle, then find the right place to cut them up.
2. Need to pay attention is the times that we can rotate is more than the length of the list. So we can get the length of list first, then the times to rotate is k%l. But in the loop, we should go len-k%len times.

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...