提交 5d8c4599 编写于 作者: L liu13

20190311

上级 0bda8b63
package code;
/*
* 24. Swap Nodes in Pairs
* 题意:交换相邻的两个节点
* 难度:Medium
* 分类:Linked List
* 思路:递归的方法,递归交换后续节点以后,再交换现在的两个节点
* 非递归的方法,需要保存三个节点,加一个头节点指向head
* Tips:
*/
public class lc24 {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode swapPairs(ListNode head) {
if( head==null||head.next==null ) return head;
return helper(head); //用递归的方法,因为交换了两个以后,第二个节点的下一个节点必须等后边两个节点交换了以后才知道谁在前
}
public ListNode helper(ListNode head){
if(head==null) return null;
if(head.next == null) return head; //节点数可能是奇数
ListNode res = head.next;
ListNode ln1 = head, ln2 = head.next, ln3 = ln2.next;
ln2.next = ln1;
ln1.next = helper(ln3);
return res;
}
}
package code;
/*
* 27. Remove Element
* 题意:移除掉数组中指定的值,返回移除后数组的长度
* 难度:Easy
* 分类:Array, Two Pointers
* 思路:两个指针,分别O(n),指向要交换的位置和和他交换的数
* 答案中直接遍历一遍数组,放到位置上就行了,i++
* Tips:
*/
public class lc27 {
public int removeElement(int[] nums, int val) {
int p1 = 0, p2 = 0;
while(p2<nums.length){
while(p1<nums.length&&nums[p1]!=val) p1++; //p1指向要交换val的位置
p2=p1;
while(p2<nums.length&&nums[p2]==val) p2++;
if(p1<nums.length && p2<nums.length){
int temp = nums[p1];
nums[p1] = nums[p2];
nums[p2] = temp;
}
}
return p1;
}
public int removeElement2(int[] nums, int val) {
int i = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册