Skip to content

Commit f7ada31

Browse files
Merge pull request #88 from PsycheYih/master
1st week leetcode solutions
2 parents 03eb5c3 + cea8e34 commit f7ada31

File tree

4 files changed

+91
-0
lines changed

4 files changed

+91
-0
lines changed

Week_01/id_46/leetcode_21_046.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
class Solution {
10+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
11+
if(l1 == null)
12+
return l2;
13+
if(l2 == null)
14+
return l1;
15+
if(l1.val >= l2.val){
16+
l2.next = mergeTwoLists(l1, l2.next);
17+
return l2;
18+
}
19+
else{
20+
l1.next = mergeTwoLists(l1.next, l2);
21+
return l1;
22+
}
23+
}
24+
25+
}

Week_01/id_46/leetcode_24_046.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
class Solution {
10+
public ListNode swapPairs(ListNode head) {
11+
//递归
12+
//终止条件
13+
if(head == null || head.next == null)
14+
return head;
15+
//单元执行:交换head和head的下一个节点
16+
ListNode next = head.next;
17+
head.next = swapPairs(next.next);
18+
next.next = head;
19+
//返回值
20+
return next;
21+
22+
}
23+
24+
}

Week_01/id_46/leetcode_24_2_046.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
class Solution {
10+
public ListNode swapPairs(ListNode head) {
11+
//递归
12+
//终止条件
13+
if(head == null || head.next == null)
14+
return head;
15+
//单元执行:交换head和head的下一个节点
16+
ListNode next = head.next;
17+
head.next = swapPairs(next.next);
18+
next.next = head;
19+
//返回值
20+
return next;
21+
22+
}
23+
24+
}

Week_01/id_46/leetcode_26_046.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public int removeDuplicates(int[] nums) {
3+
if(nums.length == 0) return 0;
4+
5+
int cur = 0;
6+
for(int i = 0 ; i < nums.length ; i++){
7+
if(nums[i] != nums[cur]){
8+
cur++;
9+
nums[cur] = nums[i];
10+
}
11+
}
12+
return cur + 1;
13+
}
14+
}
15+
/*思路:
16+
1、暴力解法,用两个变量进行存储,a存储中间值,b存储当前位置,a初始值为下标为0的数组元素值,b为0,for循环遍历数组,当发现数组值与变量值不同时,将当前数组值替换给a,数组下标为b+1的元素替换为a,b自增1,直到循环结束,返回b。
17+
2、经过优化之后,发现可以不需要使用两个变量来中间存储,直接用下标进行交换即可。
18+
*/

0 commit comments

Comments
 (0)