ListNode---LeetCode 141 and 881

快慢指针

ListNode head;  // 头节点
head.next; //下一节点
head.val; //节点对应值

是否为循环链表,利用快慢指针
当快慢指针相等时说明为循环列表

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null){
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while(slow != fast ){
            if(fast == null || fast.next == null){
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}

普通指针

LeetCode - 第二题
定义链表的头节点,head.next
注意l1和l2要非空

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode newList = head;
        int jinyi = 0;
        // ListNode n1 = l1;
        // ListNode n2 = l2;
        
        while(l1 != null || l2 != null || jinyi != 0 ){

            int n1 = l1 != null ? l1.val : 0 ;
            int n2 = l2 != null ? l2.val : 0 ;
            
            if ((n1 + n2 + jinyi) >= 10){
                int num = (n1 + n2 + jinyi) % 10 ;
                newList.next = new ListNode(num);
                newList = newList.next;
                jinyi = (n1 + n2 + jinyi) / 10;
            }else{
                int num = n1 + n2 + jinyi;
                newList.next = new ListNode(num);
                newList = newList.next;
                jinyi = 0;
            }
            if(l1 != null){
                l1 = l1.next;
            }
             if(l2 != null){
                l2 = l2.next;
            }
        }
        return head.next;
    }
}

对撞指针

对撞指针
在这里插入图片描述
利用对撞指针,首先对数组进行排序,当两数之和大于载重,则大的一方单独需要一艘船,j–。
当两数之和小于载重,大的一方减一,小的一方加一:j–,i++;
当i==j时,只剩一人,也需要一艘船,num++;

class Solution {
    public int numRescueBoats(int[] people, int limit) {
        Arrays.sort(people);
        int i = 0 ;
        int j = people.length - 1;
        int num = 0;
        while( i < j){
            if((people[i] + people[j]) > limit) {
                num++;
                j--;
            }else{
                j--;
                i++;
                num++;
            }
            if(i == j){
                num++;
            }
        }
        return num;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值