[force deduction time] [1154] [simple] the day of the year

Posted by durahman on Sat, 25 Dec 2021 02:19:39 +0100

Today's question is a little hard to say

1. Look at the questions

I'm a question
The title was written in great detail, and the case s given were also very good. Some special situations were taken into account.

2. Examining questions

After reading the title, you should all smile.
Ah? Right here, right here?

Is it a simple problem

There is no trap hidden in the title. If so, it can only be said that it is a common sense problem closely related to our life - leap year.
As a special year in the Gregorian calendar, we all know that in leap years, February will have the 29th day. And this is the only smoke bomb.

Look at the key points:

  1. The input is a string, and the title ensures its correctness and format (YYYY-MM-DD).
  2. The output is the number of days of the date in the current year, and the first day returns 1.
  3. Note that February of leap year will be one more day.

The focus of this question is almost all on the judgment of leap years. I thought so

3. Train of thought

Obviously, there are two points to be solved in today's problem:

  1. Parse the input string.
  2. Leap year judgment.

I believe that all social animals developed in java language have the need to contact date string conversion in business.
I often use the StringUtils tool class provided by apache common package, which is simple and exciting.
But leetcode obviously won't let us use these third-party packages

In short, we still have many ways to solve problem 1.
Because the title ensures the correctness of the string, we can directly split the string through "-" and transform each part into int.
Question 2 is a matter of common sense (you can baidu if you don't understand it). A year with an integer multiple of 4, but not an integer multiple of 100, or an integer multiple of 400, is a leap year.

start!

4. Lu code

class Solution {

    public int dayOfYear(String date) {
        String[] seg = date.split("-");
        List<Integer> info = Arrays.stream(seg).map(Integer::parseInt).collect(Collectors.toList());
        Calendar calendar = new GregorianCalendar(info.get(0), info.get(1) - 1, info.get(2));
        return calendar.get(Calendar.DAY_OF_YEAR);
    }
}

This is the first edition I wrote with joy. Using Calendar and its subclasses can help us solve almost all the problems related to dates.
But... Ya's leetcode doesn't support using Calendar!

What version of jdk are you using! The convenient tools of higher language are not allowed to use! But what algorithm is there to write

No way, change it

class Solution {

    public int dayOfYear(String date) {
        List<Integer> seg = Arrays.stream(date.split("-")).map(Integer::parseInt).collect(Collectors.toList());
        //Get date
        int year = seg.get(0);
        int month = seg.get(1);
        int day = seg.get(2);

        //The day of the year on which the first day of each month is initialized
        int[] dayOfMonth = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int[] daysOfMonth = new int[12];
        daysOfMonth[0] = 0;
        for (int i = 1; i < 12; i++) {
            daysOfMonth[i] = daysOfMonth[i - 1] + dayOfMonth[i - 1];
        }

        //Note that February is + 1 day in leap years
        return day + daysOfMonth[month - 1] + (month > 2 && isLeapYear(year) ? 1 : 0);
    }

    /**
     * Conditions for judging leap years:
     * Is an integral multiple of 400, or an integral multiple of 4 but not 100
     *
     * @param year particular year
     * @return Is it a leap year
     */
    private boolean isLeapYear(int year) {
        return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
    }
}

So, the second version of the native method appeared

5. Interpretation

The isLeapYear() method is used to determine whether the year is a leap year.
The judgment logic is also as mentioned above: an integer multiple of 400 or an integer multiple of 4, but not an integer multiple of 100.

private boolean isLeapYear(int year) {
        return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
    }

In the main function, I split the string through spirt and transform each part into int. this writing method takes time, but I'm too lazy to change it.

List<Integer> seg = Arrays.stream(date.split("-")).map(Integer::parseInt).collect(Collectors.toList());
        //Get date
        int year = seg.get(0);
        int month = seg.get(1);
        int day = seg.get(2);

The following steps, as stated in the note, are to calculate the first day of each month and the day of the year. The idea of prefix and is applied here. In this way, we only need to know the month of the date, we can quickly get the first day of the month and the day of the year, and add the date to get the final answer.

		//The day of the year on which the first day of each month is initialized
		int[] dayOfMonth = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int[] daysOfMonth = new int[12];
        daysOfMonth[0] = 0;
        for (int i = 1; i < 12; i++) {
            daysOfMonth[i] = daysOfMonth[i - 1] + dayOfMonth[i - 1];
        }

Of course, don't forget the special case of leap years.

//Note that February is + 1 day in leap years
return day + daysOfMonth[month - 1] + (month > 2 && isLeapYear(year) ? 1 : 0);

6. Submit


The time ranking is surprisingly low, but I'm too lazy to optimize.
After all, the idea is so, I can accept it.

7. Chew

Both time complexity and space complexity are O(1), which should be nothing to say.

8. Stealing knowledge is not stealing

Whale! You can't use Calendar, but you can use LocalDate!
In this way, you can really finish writing one sentence:

public int dayOfYear(String date) {
        return LocalDate.parse(date).getDayOfYear();
    }

The above is the liberation of other big cattle seen in the problem solution.
In addition to relying on the official api, other practices are similar

But share it Other big cattle For reference

9. Summary

The total harvest is not much, but being good at using rich APIs in various languages will make your algorithm much simpler.
In addition, even if you don't need to implement it yourself, please remember all kinds of ideas in case of need.
Is this still an algorithm?

Simple questions, simple to do.
I wish you a happy winter solstice and remember to eat dumplings.

Topics: Algorithm leetcode