LeetCode - Sort Colors

Question Definition

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

More …

LeetCode - Remove Duplicates from Sorted Array II

Question Definition

Follow up for “Remove Duplicates”: What if duplicates are allowed at most twice?

For example, Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.

My Java Solution

public int removeDuplicates(int[] nums) {
    int dupilicates = 0;
    for(int i = 2; i < nums.length; i++){
        if(nums[i] == nums[i - 1 - dupilicates] && nums[i] == nums[i - 2 - dupilicates]){
            dupilicates++;
        }
        else if(dupilicates > 0){
            nums[i - dupilicates] = nums[i];
        }
    }
    return nums.length - dupilicates;
}

LeetCode - My Calendar II

Question Definition

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

Your class will have one 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 triple booking happens when three events have some non-empty intersection (ie., there is some time that is common to all 3 events.)

For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a triple 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 …