Merge pull request #2579 from MengyiG/mengyi203

Update problem 203 Java solution
This commit is contained in:
程序员Carl
2024-07-03 10:20:38 +08:00
committed by GitHub

View File

@ -224,9 +224,10 @@ struct ListNode* removeElements(struct ListNode* head, int val){
### Java ### Java
用原来的链表操作:
```java ```java
/** /**
* 添加虚节点方式 * 方法1
* 时间复杂度 O(n) * 时间复杂度 O(n)
* 空间复杂度 O(1) * 空间复杂度 O(1)
* @param head * @param head
@ -234,25 +235,22 @@ struct ListNode* removeElements(struct ListNode* head, int val){
* @return * @return
*/ */
public ListNode removeElements(ListNode head, int val) { public ListNode removeElements(ListNode head, int val) {
if (head == null) { while(head!=null && head.val==val) {
head = head.next;
}
ListNode curr = head;
while(curr!=null && curr.next !=null) {
if(curr.next.val == val){
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
return head; return head;
} }
// 因为删除可能涉及到头节点所以设置dummy节点统一操作
ListNode dummy = new ListNode(-1, head);
ListNode pre = dummy;
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}
/** /**
* 不添加虚拟节点方式 * 方法1
* 时间复杂度 O(n) * 时间复杂度 O(n)
* 空间复杂度 O(1) * 空间复杂度 O(1)
* @param head * @param head
@ -280,8 +278,13 @@ public ListNode removeElements(ListNode head, int val) {
} }
return head; return head;
} }
```
设置一个虚拟头结点:
```java
/** /**
* 不添加虚拟节点and pre Node方式
* 时间复杂度 O(n) * 时间复杂度 O(n)
* 空间复杂度 O(1) * 空间复杂度 O(1)
* @param head * @param head
@ -289,18 +292,21 @@ public ListNode removeElements(ListNode head, int val) {
* @return * @return
*/ */
public ListNode removeElements(ListNode head, int val) { public ListNode removeElements(ListNode head, int val) {
while(head!=null && head.val==val){ // 设置一个虚拟的头结点
head = head.next; ListNode dummy = new ListNode();
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
} }
ListNode curr = head;
while(curr!=null){
while(curr.next!=null && curr.next.val == val){
curr.next = curr.next.next;
} }
curr = curr.next; return dummy.next;
}
return head;
} }
``` ```
### Python ### Python