连续子数组的最大和&&最长无重复子数组&&判断链表中是否有环

164 阅读1分钟

NC19 连续子数组的最大和

题目链接

1、解题思路
  • 一维dp,空间可以是O(1)的。
2、代码
public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
        int s = array[0];
        int ans = s;
        for(int i = 1;i < array.length;i++){
            if(s < 0){
                s = 0;
            }
            s = s + array[i];
            if(s > ans){
                ans = s;
            }
        }
        return ans;
    }
}

NC41 最长无重复子数组

题目链接

1、解题思路
  • 滑动窗口,利用一维数组做标记。
2、代码
import java.util.*;


public class Solution {
    /**
     * 
     * @param arr int整型一维数组 the array
     * @return int整型
     */
    public int maxLength (int[] arr) {
        // write code here
        boolean[] vis = new boolean[100005];
        int ans = 1;
        int l = 0;
        int r = 0;
        while(r < arr.length){
            while(vis[arr[r]]){
                vis[arr[l]] = false;
                l++;
            }
            vis[arr[r]] = true;
            int len = r - l + 1;
            if(len > ans){
                ans = len;
            }
            r++;
        }
        return ans;
    }
}

NC4 判断链表中是否有环

题目链接

1、解题思路
  • 快慢指针
2、代码
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(slow == fast){
                return true;
            }
        }
        return false;
    }
}