Skip to content

Commit 5d8c459

Browse files
committed
20190311
1 parent 0bda8b6 commit 5d8c459

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

code/lc24.java

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package code;
2+
/*
3+
* 24. Swap Nodes in Pairs
4+
* 题意:交换相邻的两个节点
5+
* 难度:Medium
6+
* 分类:Linked List
7+
* 思路:递归的方法,递归交换后续节点以后,再交换现在的两个节点
8+
* 非递归的方法,需要保存三个节点,加一个头节点指向head
9+
* Tips:
10+
*/
11+
public class lc24 {
12+
public class ListNode {
13+
int val;
14+
ListNode next;
15+
ListNode(int x) {
16+
val = x;
17+
}
18+
}
19+
20+
public ListNode swapPairs(ListNode head) {
21+
if( head==null||head.next==null ) return head;
22+
return helper(head); //用递归的方法,因为交换了两个以后,第二个节点的下一个节点必须等后边两个节点交换了以后才知道谁在前
23+
}
24+
public ListNode helper(ListNode head){
25+
if(head==null) return null;
26+
if(head.next == null) return head; //节点数可能是奇数
27+
ListNode res = head.next;
28+
ListNode ln1 = head, ln2 = head.next, ln3 = ln2.next;
29+
ln2.next = ln1;
30+
ln1.next = helper(ln3);
31+
return res;
32+
}
33+
}

code/lc27.java

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package code;
2+
/*
3+
* 27. Remove Element
4+
* 题意:移除掉数组中指定的值,返回移除后数组的长度
5+
* 难度:Easy
6+
* 分类:Array, Two Pointers
7+
* 思路:两个指针,分别O(n),指向要交换的位置和和他交换的数
8+
* 答案中直接遍历一遍数组,放到位置上就行了,i++
9+
* Tips:
10+
*/
11+
public class lc27 {
12+
public int removeElement(int[] nums, int val) {
13+
int p1 = 0, p2 = 0;
14+
while(p2<nums.length){
15+
while(p1<nums.length&&nums[p1]!=val) p1++; //p1指向要交换val的位置
16+
p2=p1;
17+
while(p2<nums.length&&nums[p2]==val) p2++;
18+
if(p1<nums.length && p2<nums.length){
19+
int temp = nums[p1];
20+
nums[p1] = nums[p2];
21+
nums[p2] = temp;
22+
}
23+
}
24+
return p1;
25+
}
26+
27+
public int removeElement2(int[] nums, int val) {
28+
int i = 0;
29+
for (int j = 0; j < nums.length; j++) {
30+
if (nums[j] != val) {
31+
nums[i] = nums[j];
32+
i++;
33+
}
34+
}
35+
return i;
36+
}
37+
}

0 commit comments

Comments
 (0)