LeetCode - My Calendar I

Question Definition

Implement a MyCalendar class to store your events. A new event can be added if adding the event will not cause a double booking.

Your class will have the method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x < end.

A double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.)

For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar.

Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)

More …

LeetCode - Maximum Length of Repeated Subarray

Question Definition

Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.

Example 1:

Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output: 3
Explanation:
The repeated subarray with maximum length is [3, 2, 1].

Note:

  1. 1 <= len(A), len(B) <= 1000
  2. 0 <= A[i], B[i] < 100

    My Java Solution

    public int findLength(int[] A, int[] B) {
     int[][] dp = new int[A.length + 1][B.length + 1];
     int max = 0;
     for(int i = A.length - 1; i >= 0; i--){
         for(int j = B.length - 1; j >= 0; j--){
             if(A[i] == B[j]){
                 dp[i][j] = dp[i + 1][j + 1] + 1;
                 if(dp[i][j] > max)
                     max = dp[i][j];
             }else
                 dp[i][j] = 0;
         }
     }
     return max;
    }
    

LeetCode - Find the Duplicate Number

Question Definition

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

More …