이 블로그 검색

2023년 7월 30일 일요일

Java Operator Precedence

Java Operator Precedence Table

Operator Precedence Definition

Operator precedence is not about calculating operations based on priority. When there are multiple operators in a complex expression, operator precedence is used to group them.

This does not determine the order of execution of operations.

Example

Suppose we have the following expression, and the computer needs to decide whether to evaluate a > 0 first or 0 && b.

int a = 1, b = 1;
a > 0 && b - ++a == 1;

Following the Java Operator Precedence Table, we start grouping the expression:

a > 0 && b - ++a == 1;

a > 0 && b - (++a) == 1;

a > 0 && (b - (++a)) == 1;

a > 0 && (b - (++a)) == 1;

(a > 0) && (b - (++a)) == 1;

(a > 0) && ((b - (++a)) == 1);

Now, we evaluate the Logical AND from left to right:

(1 > 0) && ((b - (++a)) == 1);

true && ((b - (++a)) == 1);

true && ((b - (++1)) == 1);

Next, we apply the pre-Increment unary operator, increasing the operand's value by 1 before other calculations:

true && ((b - 2) == 1);

true && ((1 - 2) == 1);

true && (-1 == 1);

true && false;

false;

Increment and Decrement Operators

Operator Description
++A Increases the operand's value by 1 before other calculations
--A Decreases the operand's value by 1 before other calculations
A++ Increases the operand's value by 1 after other calculations
A-- Decreases the operand's value by 1 after other calculations

Logical OR Operator

The logical OR operator (||) evaluates expressions from left to right. If the first expression is true, it doesn't evaluate the second expression, as only one true result is required.

(1 == 1) || (1 == 2);

In the above case, (1 == 1) is true, so (1 == 2) is not evaluated, and the result is immediately true.

2023년 7월 28일 금요일

LeetCode 42. Trapping Rain Water Java Solution

Problem

Trapping Rain Water - LeetCode

Problem-solving approach

  • At least three elements (1, 0, 1) are required to hold water, so we need a minimum of three elements.
  • Algorithm
  • We find the highest blocks on the left and right sides with respect to the position we want to check.


  • We can fill water up to the minimum of these two heights.
  • Now, we subtract the block's height at the position to get the height of the water that can be filled.

  • Repeat the process for all positions.
  • To use the above algorithm, we need to loop in advance to get the highest block on the right and left.

  • Below, you can see the necessary values for each position.




Github Link

https://github.com/eunhanlee/LeetCode_42_TrappingRainWater_Solution.git

Time Complexity: O(n), Space Complexity: O(n)

public class Solution {
    /**
     * Calculates the amount of water that can be trapped between bars.
     *
     * @param height An array representing the height of the bars
     * @return The total amount of water trapped between bars
     */
    public static int trap(int[] height) {
        int n = height.length;
        if (n <= 2) {
            return 0;
        }

        // An array to store the maximum heights of the bars on the left side of each index
        int[] leftMax = new int[n];
        // An array to store the maximum heights of the bars on the right side of each index
        int[] rightMax = new int[n];
        // A variable to store the total amount of trapped water
        int maxWater = 0;

        // Calculate the maximum heights of the bars on the left side of each index
        leftMax[0] = height[0];
        for (int i = 1; i < n; i++) {
            leftMax[i] = Math.max(leftMax[i - 1], height[i]);
        }

        // Calculate the maximum heights of the bars on the right side of each index
        rightMax[n - 1] = height[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            rightMax[i] = Math.max(rightMax[i + 1], height[i]);
        }

        // Calculate the trapped water for each bar
        for (int i = 1; i < n - 1; i++) {
            // Find the minimum height between the current bar's left and right highest bars
            int minBarHeight = Math.min(leftMax[i], rightMax[i]);
            // If the minimum bar height is greater than the current bar's height,
            // water can be trapped on top of the current bar.
            if (minBarHeight > height[i]) {
                // The trapped water amount is the difference between the minimum bar height and the current bar's height.
                maxWater += minBarHeight - height[i];
            }
        }

        // Return the total amount of trapped water.
        return maxWater;
    }
}

LeetCode 771. Jewels and Stones Java Solution

Problem

Jewels and Stones - LeetCode

Solution Approach

  • This problem is about checking whether each character from one input string exists in another input string.
  • Since each character needs to be checked at least once, the time complexity is O(n^2), where n is the length of the input string.
  • It tests your basic string handling skills.
  • To solve it, you need to understand the toCharArray() method and how to compare characters using the char data type in Java.

Java's Primitive Data Types and Reference Data Types

Github Link

https://github.com/eunhanlee/LeetCode_771_JewelsandStones_Solution.git

Time Complexity: O(n^2), Space Complexity: O(1)

class Solution {
    /**
     * Method to count the number of jewels in the stones.
     *
     * @param jewels The string representing types of jewels.
     * @param stones The string representing the stones you have.
     * @return The number of jewels found in the stones.
     */
    public int numJewelsInStones(String jewels, String stones) {
        int counter = 0;

        for (char stone : stones.toCharArray()) {
            for (char jewel : jewels.toCharArray()) {
                if (stone == jewel) {
                    counter++;
                }
            }
        }

        return counter;
    }
}

Java's Primitive Data Types and Reference Data Types

Primitive Types

  • There are a total of 8 primitive types predefined and provided.
  • As they have default values, they do not have Null.
  • They are stored in the stack memory, which is the space for storing actual values.
  • String is an object and not a primitive type.

Reference Types

  • All types except primitive types are reference types.
  • Null, which represents an empty object, exists in reference types.
  • The space for storing the address value of the location where the value is stored is in the heap memory.
  • There are no syntax errors, but runtime errors occur when using Null for objects or arrays, leading to a NullPointException. Therefore, variables should be assigned values.

LeetCode 35. Search Insert Position Java Solution

Problem

Search Insert Position - LeetCode

Problem Solving Approach

  • The given problem deals with a sorted array.
  • The condition is to solve it in O(log n) time complexity.
  • The only method to achieve this in a sorted list is Binary Search.
  • This problem tests your understanding of Binary Search and its implementation.
  • When implementing Binary Search, you need to decide whether to use recursion or iteration.
  • Since this problem does not require previous results or sub-problems, it is more effective to implement it using iteration.
  • When the target value is not found, the function should return the index where the target should be inserted.
  • The function returns 'low' value because it is closer to the target than 'high', where 'mid' is unchanged and 'mid' divided by 2 and floored is less than or equal to 'high'.

Github Link

https://github.com/eunhanlee/LeetCode_35_SearchInsertPosition_Solution.git

Time Complexity: O(log n), Space Complexity: O(1)

class Solution {
    /**
     * Search for the insertion position of the target value in the given sorted array.
     *
     * @param nums   Sorted integer array.
     * @param target Value to search for.
     * @return The index where the target should be inserted.
     */
    public int searchInsert(int[] nums, int target) {
        int low = 0;
        int high = nums.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2;

            if (nums[mid] == target)
                return mid; // Return the index if the target value exists.
            else if (nums[mid] < target)
                low = mid + 1; // Move to the right half if the target is greater than the current middle value.
            else
                high = mid - 1; // Move to the left half if the target is less than the current middle value.
        }

        // If the loop exits, it means the target does not exist in the array, and 'low' indicates the insertion position.
        return low;
    }
}

2023년 7월 24일 월요일

LeetCode 1603. Design Parking System Solution

Problem

Design Parking System - LeetCode

Approach to Problem Solving

  • This is a question about object creation in Java.
  • The first solution demonstrates basic object creation, making it suitable for collaboration and future updates.
  • The second solution is highly efficient for this specific problem, but it might be challenging to update later.

Github Link

https://github.com/eunhanlee/LeetCode_1603_DesignParkingSystem_Solution.git

1st Solution

class ParkingSystem {
    private int bigSlots;
    private int mediumSlots;
    private int smallSlots;

    /**
     * Creates a new ParkingSystem with specified slots for each vehicle type.
     *
     * @param big    Number of available slots for big vehicles.
     * @param medium Number of available slots for medium vehicles.
     * @param small  Number of available slots for small vehicles.
     */
    public ParkingSystem(int big, int medium, int small) {
        this.bigSlots = big;
        this.mediumSlots = medium;
        this.smallSlots = small;
    }

    /**
     * Adds a vehicle of the given type to the parking system.
     *
     * @param carType Type of the vehicle to be parked (1 for big, 2 for medium, 3 for small).
     * @return True if the vehicle is successfully parked, otherwise false.
     */
    public boolean addCar(int carType) {
        switch (carType) {
            case 1:
                if (this.bigSlots > 0) {
                    this.bigSlots--;
                    return true;
                }
                break;
            case 2:
                if (this.mediumSlots > 0) {
                    this.mediumSlots--;
                    return true;
                }
                break;
            case 3:
                if (this.smallSlots > 0) {
                    this.smallSlots--;
                    return true;
                }
                break;
        }
        return false;
    }
}

2nd Solution

class ParkingSystem {
    int[] slots;

    /**
     * Creates a new parking system with given slot sizes.
     *
     * @param big    Number of slots available for big vehicles.
     * @param medium Number of slots available for medium vehicles.
     * @param small  Number of slots available for small vehicles.
     */
    public ParkingSystem(int big, int medium, int small) {
        slots = new int[]{big, medium, small};
    }

    /**
     * Adds a vehicle of the given type to the parking system.
     *
     * @param carType Type of the vehicle to be parked (1 for big, 2 for medium, 3 for small).
     * @return True if the vehicle is successfully parked, otherwise false.
     */
    public boolean addCar(int carType) {
        return --slots[carType - 1] >= 0;
    }
}

Reference

Reasons for Using 'this' Keyword in Java Object Creation

What is Short Circuit Evaluation

Short Circuit Evaluation

Short Circuit Evaluation refers to the behavior in logical AND and OR operations where the result can be determined without evaluating the remaining operands if the outcome is already certain.

Applicable Programming Languages

As of the current date in 2023, Short Circuit Evaluation is confirmed to be applicable in C, C++, Java, and Python.

Short Circuit Evaluation in AND Operation

In the case of AND operation, if the first operand evaluates to false, the remaining operands are skipped, and the result is determined as false.

Short Circuit Evaluation in OR Operation

For the OR operation, if the first operand evaluates to true, the remaining operands are skipped, and the result is determined as true.

Logic Gate Truth Tables & Definitions

Logic Gate Truth Tables Java Code !A // NOT A&B // AND ~(A&B) // NAND A|B // OR ~(A|B) // XOR A^B // XOR ~(A^B) // XNOR ~A // Inve...