7/29, FB, Excel Sheet, Remove Duplicates
Excel Sheet Column Title
public class Solution {
public String convertToTitle(int n) {
StringBuilder sb = new StringBuilder();
while(n>0){
n--;
char c = (char) (n % 26 + 'A');
sb.append(c);
n = n/26;
}
sb.reverse();
return sb.toString();
}
}
Excel Sheet Column Number
public class Solution {
public int titleToNumber(String s) {
if(s == null || s.length()==0)
return 0;
int result = 0;
for(int i = 0;i<s.length();i++){
result *= 26;
result += (int) (s.charAt(i) - 'A') + 1;
}
return result;
}
}
Remove Duplicates from Sorted Array II
two pointer
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length == 0) return 0;
if(nums.length <= 2) return nums.length;
int ptr = 2;
for(int i = 2; i < nums.length; i++){
if(nums[i] == nums[ptr - 1] && nums[i] == nums[ptr - 2]) continue;
else nums[ptr++] = nums[i];
}
return ptr;
}
}
public int removeDuplicates(int[] nums) {
if(nums==null || nums.length<=2) return nums.length;
int idx = 0;
for(int i=0;i<nums.length;i++){
if(idx<2 || nums[i]>nums[idx-2]) nums[idx++] = nums[i];
}
return idx;
}
Remove Duplicates from Sorted List II
也挺简单的,但是多了几个细节:
这次是只要是 duplicate 就全跳过;
因此看到一截重复的就全部跳过,但同时要注意不要假设一段重复的后面不会接着出现另外一段;所以处理完一段直接 continue;
dummy node 不能无脑连 head ,没准 head 里面的一个都不取,所以就建个 dummy 之后 next 先空着,自己一个一个加上去;这里注意要新建node,不能用原来的node. 否则next指针指向有问题.[1,2,2]会返回[1,2,2];
从 dummy 出发的 cur 连完了之后,要记得循环结束时切断尾巴,因为我们在循环中只跳过,没切断,最后的收尾要自己做一下。
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode dummyhead = dummy;
ListNode cur = head; boolean dup = false;
while(cur!=null){
while(cur!=null && cur.next!=null && cur.val == cur.next.val){
dup = true; cur = cur.next;
}
if(!dup){
//System.out.println("add: " + cur.val);
dummy.next = new ListNode(cur.val); dummy = dummy.next;
}
dup = false;
cur = cur.next;
}
return dummyhead.next;
}