Skip to content

1st week leetcode solutions #88

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 24, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Week_01/id_46/leetcode_21_046.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null)
return l2;
if(l2 == null)
return l1;
if(l1.val >= l2.val){
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
else{
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}
}

}
24 changes: 24 additions & 0 deletions Week_01/id_46/leetcode_24_046.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
//递归
//终止条件
if(head == null || head.next == null)
return head;
//单元执行:交换head和head的下一个节点
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
//返回值
return next;

}

}
24 changes: 24 additions & 0 deletions Week_01/id_46/leetcode_24_2_046.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
//递归
//终止条件
if(head == null || head.next == null)
return head;
//单元执行:交换head和head的下一个节点
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
//返回值
return next;

}

}
18 changes: 18 additions & 0 deletions Week_01/id_46/leetcode_26_046.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0) return 0;

int cur = 0;
for(int i = 0 ; i < nums.length ; i++){
if(nums[i] != nums[cur]){
cur++;
nums[cur] = nums[i];
}
}
return cur + 1;
}
}
/*思路:
1、暴力解法,用两个变量进行存储,a存储中间值,b存储当前位置,a初始值为下标为0的数组元素值,b为0,for循环遍历数组,当发现数组值与变量值不同时,将当前数组值替换给a,数组下标为b+1的元素替换为a,b自增1,直到循环结束,返回b。
2、经过优化之后,发现可以不需要使用两个变量来中间存储,直接用下标进行交换即可。
*/