CodeTop每日系列三题------------------2021.11.20
作者:互联网
LC56. 合并区间
class Solution {
public int[][] merge(int[][] intervals) {
//先排序
Arrays.sort(intervals,(v1,v2) -> v1[0] - v2[0]);
//创建一个list存放结果
List<int[]> merged = new ArrayList();
//判断区间是否重合
for(int[] interval:intervals){
//如果列表为空或者没有重复区间那么可以直接加
//也就是上一个区间的右侧要小于当前区间的左侧
if(merged.size() == 0 || merged.get(merged.size() - 1)[1] < interval[0]){
merged.add(interval);
}else{
//合并上一个区间,也就是上一个区间的右侧要和当前区间的右侧取一个较大的值
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1],interval[1]);
}
}
return merged.toArray(new int[merged.size()][2]);
}
}
LC69. Sqrt(x)
注:主要是在0 - x 的区间范围当中找一个数的平方小于等于x,考虑二分搜索收缩边界最后返回答案
class Solution {
public int mySqrt(int x) {
int ans = 0,left = 0,right = x;
while(left <= right){
int mid = left + (right - left) / 2;
if((long) mid * mid <= x){
ans = mid;
left = mid + 1;
}else{
right = mid - 1;
}
}
return ans;
}
}
LC82. 删除排序链表中的重复元素 II
/**
* 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) {
ListNode dummy = new ListNode(0,head);
ListNode cur = dummy;
while(cur.next != null && cur.next.next != null){
if(cur.next.val == cur.next.next.val){
int x = cur.next.val;
while(cur.next != null && cur.next.val == x){
cur.next = cur.next.next;
}
}else{
cur = cur.next;
}
}
return dummy.next;
}
}
标签:三题,20,cur,val,------------------,next,int,ListNode,merged 来源: https://blog.csdn.net/weixin_44004649/article/details/121437733