1.
给定一个已排序的链表的头 head
, 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
题解:
由于链表已经排序好,重复数字的节点一定是连续的,所以进行一次遍历,就可以删除重复的元素。需要注意的是头节点是可能被删除的,所以要设置一个哑节点(dummy node)指向头节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null) return null;
ListNode dummyHead = new ListNode(-101);
ListNode pre = dummyHead;
pre.next = head;
ListNode cur = head;
while(cur != null && cur.next!=null){
if(cur.val == cur.next.val){
int val = cur.val;
while(cur != null && cur.val==val){
cur = cur.next;
}
pre.next = cur;
}else{
pre = cur;
cur = cur.next;
}
}
return dummyHead.next;
}
}
2.
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
题解:
难点:去除重复解
操作:1.首先判断数组是否为空或者长度小于3,如果是,返回[]
2.对数组进行排序
3.遍历排序后数组
①若nums[i]>0,因为已排序号不可能有三个元素之和等于0,直接返回结果
②对于重复元素,跳过,避免重复解。
③令左指针L=i+1,右指针R=n-1,当L<R时,执行循环:
当nums[i]+nums[L]+nums[R]==0执行循环,判断左界和右界是否和下一位置重复,去除重复解。同时将L,R移到下一位置,寻找新解。
若和大于0,说明nums[R]太大,R左移
若和小于0,说明nums[L]太小,L右移
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n=len(nums)
res=[]
if(not nums or n<3):
return []
nums.sort()
res=[]
for i in range(n):
if(nums[i]>0):
return res
if(i>0 and nums[i]==nums[i-1]):
continue
L=i+1
R=n-1
while(L<R):
if(nums[i]+nums[L]+nums[R]==0):
res.append([nums[i],nums[L],nums[R]])
while(L<R and nums[L]==nums[L+1]):
L=L+1
while(L<R and nums[R]==nums[R-1]):
R=R-1
L=L+1
R=R-1
elif(nums[i]+nums[L]+nums[R]>0):
R=R-1
else:
L=L+1
return res