其他分享
首页 > 其他分享> > 力扣---2020.10.9

力扣---2020.10.9

作者:互联网

141. 环形链表

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null){
            return false;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while(fast != slow){
            if(fast.next == null || fast.next.next == null){
                return false;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        return true;
    }
}
public boolean hasCycle(ListNode head) {
    if (head == null)
        return false;
    //快慢两个指针
    ListNode slow = head;
    ListNode fast = head;
    while (fast != null && fast.next != null) {
        //慢指针每次走一步
        slow = slow.next;
        //快指针每次走两步
        fast = fast.next.next;
        //如果相遇,说明有环,直接返回true
        if (slow == fast)
            return true;
    }
    //否则就是没环
    return false;
}

55. 跳跃游戏

class Solution {
    public boolean canJump(int[] nums) {
        int maxStep = 0;
        for(int i = 0;i < nums.length;i++){
            if(i <= maxStep){
                maxStep = Math.max(maxStep,i+nums[i]);
                if(maxStep>=nums.length-1){
                    return true;
                }
            }
        }
        return false;
    }
}
class Solution {
    public boolean canJump(int[] nums) {
        int maxStep = 0;
        for(int i = 0;i < nums.length;i++){
            if(i > maxStep) return false;
            maxStep = Math.max(maxStep,i+nums[i]);
        }
        return true;
    }
}

75. 颜色分类

class Solution {
    public void sortColors(int[] nums) {
        int left = 0,right = nums.length-1;
        for(int i = left;i <= right;i++){
            if(nums[i]==0){
                nums[i] = nums[left];
                nums[left] = 0;
                left++;
            }else if(nums[i]==2){
                nums[i--] = nums[right];
                nums[right] = 2;
                right--;
            }
        }
    }
}

public class Solution {
    public void sortColors(int[] nums) {
        int len = nums.length;
        if (len < 2) {
            return;
        }

        int zero = 0;
        int two = len;
        int i = 0;
        
        while (i < two) {
            if (nums[i] == 0) {
                swap(nums, i, zero);
                zero++;
                i++;
            } else if (nums[i] == 1) {
                i++;
            } else {
                two--;
                swap(nums, i, two);
            }
        }
    }

    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }
}

你知道的越多,你不知道的越多。

标签:---,head,return,nums,int,fast,next,力扣,2020.10
来源: https://blog.csdn.net/qq_40722827/article/details/108987130