代码简洁
-
舍弃用不到的变量
-
如果需要判断输入为空且有返回值,那么可以直接返回输入
- 例1:
/**
* 我的代码
*/
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return null; //这里可以把判断放进while的条件里
ListNode temp = head;
//这个变量可以省略
int tempValue = head.val;
while(temp.next != null){
if(tempValue == temp.next.val){
if(temp.next.next != null){
temp.next = temp.next.next;
}else{
temp.next = null;
}
}else{
temp = temp.next;
tempValue = temp.val;
}
}
return head;
}
简化之后的代码:
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.next.val == current.val) {
//我之前判断了一下next.next为空的情况,其实没必要,
//为空的话也可以直接把空赋值给current的next
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
更为简洁的版本:
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)return head;
//递归用时最短
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}
- 例2:
if(left.val == right.val){
return isSymmetric(left.left, right.right) &&
isSymmetric(left.right, right.left);
}
return false;
改善之后:
return (t1.val == t2.val) &&
isMirror(t1.right, t2.left) &&
isMirror(t1.left, t2.right);
数组操作
- 涉及到下标的一定要注意越界问题
- 单个数组元素前移/后移问题举例:
错误:
//后移nums1的元素
for(int i = n; i < n + m; i ++) {
nums1[i] = nums1[i - n];
}
这里之所以错了是因为被替换过的数据被用来更新新的位置(类似于脏读)
改正:
//后移nums1的元素
for(int i = m + n - 1; i >= n; i --) {
nums1[i] = nums1[i - n];
}