18.删除链表的节点
思想:先找到要删除的节点的前一个节点,p指针指向它
注意:判断空链表,单个节点的链表等等。
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head==null){
return head;
}
ListNode p = head;
if(head.val==val){
return p.next;
}
while(p.next != null){
if(p.next.val==val){
break;
}
p = p.next;
}
if(p.next.next!=null)
p.next = p.next.next;
else
p.next = null;
return head;
}
}
21.调整数组顺序使奇数位于偶数前面
思路一:头尾双指针 O(n) ,O(1)
left指向数组头,right指向数组尾
left右移直到指向了偶数
right左移直到指向了奇数
如果left此时已经大于right,break结束循环
交换left和right所指数字
继续以上步骤,直到left > right
class Solution {
public int[] exchange(int[] nums) {
int l = 0, r = nums.length - 1;
while(l <= r){
while(l <= r && nums[l] % 2 == 1)
l++;
while(l <= r && nums[r] % 2 == 0)
r--;
if(l > r)
break;
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
}
return nums;
}
}
思路二:辅助数组 O(n) ,O(n)
Java:遍历两边nums,第一遍遍历奇数,放在res数组中,第二遍遍历偶数,继续添加到res数组中。
class Solution {
public int[] exchange(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int index = 0;
for(int num : nums){
if(num % 2 == 1){
res[index++] = num;
}
}
for(int num : nums){
if(num % 2 == 0){
res[index++] = num;
}
}
return res;
}
}
思路三:快慢双指针 O(n) ,O(1)
slow和fast都从数组的头部开始遍历
fast正常一步一步右移
如果fast遇到了奇数,和slow位置的数字互换,slow++,fast++
如果fast没有遇到奇数,继续右移,fast++
fast遍历到末尾时结束遍历
class Solution {
public int[] exchange(int[] nums) {
int slow = 0, fast = 0;
while(fast < nums.length){
if(nums[fast] % 2 == 1){
int tmp = nums[slow];
nums[slow] = nums[fast];
nums[fast] = tmp;
slow++;
}
fast++;
}
return nums;
}
}