diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9cd9a49 --- /dev/null +++ b/.gitignore @@ -0,0 +1,36 @@ +/Algorithm.iml + +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ +/out/ diff --git a/main.py b/main.py new file mode 100644 index 0000000..233aea2 --- /dev/null +++ b/main.py @@ -0,0 +1,145 @@ +import os +import requests +import argparse +from mdcal import update_calendar + + +def get_issue(issue_number=None): + try: + if issue_number is None: + issue_number = os.getenv("ISSUE_NUMBER") + repo_name = os.getenv("GITHUB_REPOSITORY") + gh_token = os.getenv("GH_TOKEN") + + headers = {"Authorization": f"token {gh_token}"} + api_url = f"https://api.github.com/repos/{repo_name}/issues/{issue_number}" + + response = requests.get(api_url, headers=headers) + issue = response.json() + + print(api_url) + print(headers) + print(issue) + + except Exception as e: + print(f"Error in get_issue: {e}") + return None + + return issue + + +def update_records(issue, issue_number=None): + if issue_number is None: + issue_number = os.getenv("ISSUE_NUMBER") + + issue_title = issue["title"] + issue_labels = ["`" + label["name"] + "`" for label in issue["labels"]] + issue_link = issue["html_url"] + + with open("README.md", "r") as file: + lines = file.readlines() + + table_start_index = None + existing_issue_index = None + + for i in range(len(lines)): + if lines[i].strip() == "|#|Title|Tag|Date|": + table_start_index = i + 2 + if lines[i].strip().startswith(f"|{issue_number}|") and table_start_index: + existing_issue_index = i + if existing_issue_index: + break + + new_line = f"|{issue_number}|[{issue_title}]({issue_link})|{' '.join(issue_labels)}|{issue['created_at']}|\n" + if existing_issue_index is not None: + lines[existing_issue_index] = new_line + else: + lines.insert(table_start_index, new_line) + with open("README.md", "w") as file: + file.writelines(lines) + + return "Successfully updated Records of README.md" + +def update_star(issue): + created_at_str = issue['created_at'] + date_str = created_at_str.split("T")[0] + year, month, day = map(int, date_str.split("-")) + return update_calendar(year, month, day) + +def get_comments(issue_number=None): + try: + if issue_number is None: + issue_number = os.getenv("ISSUE_NUMBER") + + repo_name = os.getenv("GITHUB_REPOSITORY") + gh_token = os.getenv("GH_TOKEN") + + headers = {"Authorization": f"token {gh_token}"} + comments_api_url = f"https://api.github.com/repos/{repo_name}/issues/{issue_number}/comments" + + comments_response = requests.get(comments_api_url, headers=headers) + comments = comments_response.json() + + except Exception as e: + print(f"Error in get_comments: {e}") + return [] + + return comments + +def backup_issue_as_md(issue, issue_number): + try: + if issue_number is None: + issue_number = os.getenv("ISSUE_NUMBER") + + issue_title = issue["title"] + issue_body = issue['body'] + issue_labels = ["`" + label['name'] + "`" for label in issue['labels']] + issue_link = issue['html_url'] + issue_date = issue['created_at'] + + comments = get_comments(issue_number) + + if not os.path.exists("backup"): + os.mkdir("backup") + + with open(f"backup/{issue_number}#{issue_title}.md", "w") as file: + file.write("# " + issue_title + "\n\n") + file.write(issue_body + "\n\n") + file.write("---\n\n") + file.write("* Link: " + issue_link + "\n") + file.write("* Labels: " + ', '.join(issue_labels) + "\n") + file.write("* Creation Date: " + issue_date + "\n") + for i, comment in enumerate(comments, start=1): + file.write(f"\n---\n\n") + file.write(comment['body']) + file.write("\n\n*\n") + + except Exception as e: + print(f"Error in backup_issue_as_md: {e}") + return "Backup failed" + + return "Successfully backup records" + +def main(issue_number): + try: + issue = get_issue(issue_number) + if issue is not None: + print(update_records(issue, issue_number)) + print(update_star(issue)) + print(backup_issue_as_md(issue, issue_number)) + else: + print("Issue could not be retrieved.") + except Exception as e: + print(f"Error in main: {e}") + + +if __name__ == "__main__": + try: + parser = argparse.ArgumentParser() + parser.add_argument( + "--issue_number", help="issue_number", default=None, required=False + ) + args = parser.parse_args() + main(args.issue_number) + except Exception as e: + print(f"Error: {e}") diff --git a/mdcal.py b/mdcal.py new file mode 100644 index 0000000..acae135 --- /dev/null +++ b/mdcal.py @@ -0,0 +1,123 @@ +import os +import re +import calendar +from datetime import datetime +import sys + +def create_calendar(year, month, with_isoweek=False, start_from_Sun=False, lang="en"): + firstweekday = 6 if start_from_Sun else 0 + + cal = calendar.Calendar(firstweekday=firstweekday) + + mdstr = "" + dic = get_dict(lang) + + colnames = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] + if start_from_Sun: + colnames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] + if with_isoweek: + colnames.insert(0, "Week") + colnames = [dic[col] for col in colnames] + + mdstr += '|' + '|'.join(colnames) + '|' + '\n' + mdstr += '|' + '|'.join([':-:' for _ in range(len(colnames))]) + '|' + '\n' + + for days in cal.monthdatescalendar(year, month): + if with_isoweek: + isoweek = days[0].isocalendar()[1] + mdstr += '|' + str(isoweek) + '|' + \ + '|'.join([str(d.day) for d in days]) + '|' + '\n' + else: + mdstr += '|' + '|'.join([str(d.day) for d in days]) + '|' + '\n' + + return mdstr + + +def print_calendar(year, month, with_isoweek=False, start_from_Sun=False, lang="en"): + print('{}/{}\n'.format(year, month)) + print(create_calendar(year, month, with_isoweek, start_from_Sun, lang)) + + +def get_dict(lang='en'): + dic = {} + colnames = ['Week', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] + colnames_ja = ['週', '月', '火', '水', '木', '金', '土', '日'] + if lang == 'en': + for col in colnames: + dic[col] = col + elif lang == 'ja': + for col, colja in zip(colnames, colnames_ja): + dic[col] = colja + else: + for col in colnames: + dic[col] = col + return dic + +def update_calendar(year, month, day, with_isoweek=False, start_from_Sun=False, lang="en"): + # Check if README.md exists, if not, create one + if not os.path.exists('README.md'): + with open('README.md', 'w') as f: + print("The file README.md does not exist. Creating a new one...") + f.write('## 🎯 Calendar\n\n## Records\n\n') + + # Read the content of README.md + with open('README.md', 'r') as file: + content = file.read() + + # Extract the part between "## 🎯 Calendar" to the start of the next section "## Records". + calendar_section_match = re.search("## 🎯 Calendar(.*)(?=## 🍃 Records)", content, re.DOTALL) + + # If "## 🎯 Calendar" section doesn't exist or there is no calendar data + if calendar_section_match is None: + return "The 'Calendar' section does not exist in README.md or there is no calendar data." + + calendar_section = calendar_section_match.group(1) + + # Check if the current month/year already exists in the calendar + current_month_exists = "* {}/{}\n".format(year, month) in calendar_section + calendar_section_lines = ["## 🎯 Calendar\n"] + + if not current_month_exists: + # Create the calendar for the current month/year and append it + cal = create_calendar(year, month, with_isoweek, start_from_Sun, lang) + calendar_section_lines.append('* {}/{}\n'.format(year, month)) + calendar_section_lines += cal.split("\n") + calendar_section_lines.append('\n') + else: + # Append the existing calendar for the current month/year + calendar_section_lines += calendar_section.split("\n")[2:] + + star_flag = True + month_start_flag = False + for i in range(4, len(calendar_section_lines)): + if re.match("^\\|([ ]*.*[ ]*\|)+$", calendar_section_lines[i]): + day_cells = calendar_section_lines[i].split("|") + for j in range(1, len(day_cells) - 1): + digit = re.findall(r'\d+', day_cells[j].strip()) + if len(digit) == 0: + continue + if digit[0] == "1": + month_start_flag = True + if digit[0] == str(day) and "🌟" not in day_cells[j] and star_flag and month_start_flag: + day_cells[j] = day_cells[j].strip() + "🌟" + star_flag = False + calendar_section_lines[i] = "|".join(day_cells) + + # Replace 'Calendar' section in README.md with the updated section + new_content = re.sub(r"## 🎯 Calendar(.*)(?=## 🍃 Records)", "\n".join(calendar_section_lines), content, flags=re.DOTALL) + + with open('README.md', 'w') as file: + file.write(new_content) + + return "Successfully updated Calendar of README.md" + +if __name__ == "__main__": + argv = sys.argv + if len(argv) == 3: + year, month = [int(a) for a in argv[1:3]] + print(update_calendar(year, month, datetime.now().day)) + elif len(argv) == 4: + year, month, day = [int(a) for a in argv[1:4]] + print(update_calendar(year, month, day)) + else: + print('Usage: python mdcal.py [year] [month] [day]') \ No newline at end of file diff --git a/src/Top100Liked/leetcode/editor/cn/FindAllAnagramsInAString.java b/src/Top100Liked/leetcode/editor/cn/FindAllAnagramsInAString.java index 12e39b9..15f87cb 100644 --- a/src/Top100Liked/leetcode/editor/cn/FindAllAnagramsInAString.java +++ b/src/Top100Liked/leetcode/editor/cn/FindAllAnagramsInAString.java @@ -36,17 +36,49 @@ // // Related Topics 哈希表 字符串 滑动窗口 👍 1372 👎 0 -// package Top100Liked.leetcode.editor.cn; -// public class FindAllAnagramsInAString{ -// public static void main(String[] args) { -// Solution solution = new FindAllAnagramsInAString().new Solution(); -// } -// //leetcode submit region begin(Prohibit modification and deletion) -// class Solution { -// public List findAnagrams(String s, String p) { -// -// } -// } -//// leetcode submit region end(Prohibit modification and deletion) +package Top100Liked.leetcode.editor.cn; -// } +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class FindAllAnagramsInAString { + public static void main(String[] args) { + Solution solution = new FindAllAnagramsInAString().new Solution(); + System.out.println(solution.findAnagrams("cbaebabacd", "abc")); + } + + //leetcode submit region begin(Prohibit modification and deletion) + class Solution { + public List findAnagrams(String s, String p) { + char[] sCharArray = s.toCharArray(), pCharArray = p.toCharArray(); + int right = 0, sLength = sCharArray.length, pLength = pCharArray.length; + List result = new ArrayList<>(); + if (pLength > sLength || 0 == sLength) { + return result; + } + int[] sArr = new int[26], pArr = new int[26]; + for (int i = 0; i < pLength; i++) { + pArr[pCharArray[i] - 'a']++; + sArr[sCharArray[i] - 'a']++; + } + if (Arrays.equals(pArr, sArr)) { + result.add(0); + } + for (int i = 0; i < (sCharArray.length - pLength); i++) { + sArr[sCharArray[i] - 'a']--; + sArr[sCharArray[i + pLength] - 'a']++; +// String string = IntStream.range(0, sArr.length) +// .filter(index -> sArr[index] != 0) +// .mapToObj(index -> String.valueOf((char) (index + 'a'))) +// .collect(Collectors.joining()); + if (Arrays.equals(pArr, sArr)) { + result.add(i + 1); + } + } + return result; + } + } +// leetcode submit region end(Prohibit modification and deletion) + +} diff --git a/src/Top100Liked/leetcode/editor/cn/LongestSubstringWithoutRepeatingCharacters.java b/src/Top100Liked/leetcode/editor/cn/LongestSubstringWithoutRepeatingCharacters.java index 7cb6620..1eed21c 100644 --- a/src/Top100Liked/leetcode/editor/cn/LongestSubstringWithoutRepeatingCharacters.java +++ b/src/Top100Liked/leetcode/editor/cn/LongestSubstringWithoutRepeatingCharacters.java @@ -46,12 +46,14 @@ public class LongestSubstringWithoutRepeatingCharacters { public static void main(String[] args) { Solution solution = new LongestSubstringWithoutRepeatingCharacters().new Solution(); - System.out.println(solution.lengthOfLongestSubstring("dvdf")); + System.out.println(solution.lengthOfLongestSubstring("abcabcbb")); } + // leetcode submit region begin(Prohibit modification and deletion) class Solution { public int lengthOfLongestSubstring(String s) { char[] charArray = s.toCharArray(); + int result = 0, right = 0, length = charArray.length; if (charArray.length == 0) { return 0; } else if (charArray.length == 1) { @@ -59,19 +61,17 @@ public int lengthOfLongestSubstring(String s) { } else if (s.isBlank()) { return 1; } - int result = 0, right = -1; Set mySet = new HashSet<>(); for (int i = 0; i < charArray.length; i++) { if (i != 0) { mySet.remove(charArray[i - 1]); } - while (right < charArray.length - 1 && !mySet.contains(charArray[right + 1])) { - mySet.add(charArray[right + 1]); + while (right < length && !mySet.contains(charArray[right])) { + mySet.add(charArray[right]); right++; } - result = Math.max(result, right - i + 1); + result = Math.max(result, right - i); } - return result; } } diff --git a/src/Top100Liked/leetcode/editor/cn/MaximumSubarray.java b/src/Top100Liked/leetcode/editor/cn/MaximumSubarray.java new file mode 100644 index 0000000..4c179b7 --- /dev/null +++ b/src/Top100Liked/leetcode/editor/cn/MaximumSubarray.java @@ -0,0 +1,73 @@ +//给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 +// +// 子数组 是数组中的一个连续部分。 +// +// +// +// 示例 1: +// +// +//输入:nums = [-2,1,-3,4,-1,2,1,-5,4] +//输出:6 +//解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。 +// +// +// 示例 2: +// +// +//输入:nums = [1] +//输出:1 +// +// +// 示例 3: +// +// +//输入:nums = [5,4,-1,7,8] +//输出:23 +// +// +// +// +// 提示: +// +// +// 1 <= nums.length <= 10⁵ +// -10⁴ <= nums[i] <= 10⁴ +// +// +// +// +// 进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。 +// +// Related Topics 数组 分治 动态规划 👍 6532 👎 0 + + +package Top100Liked.leetcode.editor.cn; + +public class MaximumSubarray { + public static void main(String[] args) { + Solution solution = new MaximumSubarray().new Solution(); + System.out.println(solution.maxSubArray(new int[]{-1,-2})); + } + + //leetcode submit region begin(Prohibit modification and deletion) + class Solution { + public int maxSubArray(int[] nums) { + int len = nums.length, result = nums[0]; + if (len == 0) { + return 0; + } else if (len == 1) { + return nums[0]; + } + int[] res = new int[len]; + res[0] = nums[0]; + for (int i = 1; i < nums.length; i++) { + res[i] = Math.max(nums[i], nums[i] + res[i - 1]); + result = Math.max(result, res[i]); + } + return result; + } + } +//leetcode submit region end(Prohibit modification and deletion) + +} \ No newline at end of file diff --git a/src/Top100Liked/leetcode/editor/cn/MergeIntervals.java b/src/Top100Liked/leetcode/editor/cn/MergeIntervals.java new file mode 100644 index 0000000..8d8d5f7 --- /dev/null +++ b/src/Top100Liked/leetcode/editor/cn/MergeIntervals.java @@ -0,0 +1,73 @@ +//以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返 +//回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。 +// +// +// +// 示例 1: +// +// +//输入:intervals = [[1,3],[2,6],[8,10],[15,18]] +//输出:[[1,6],[8,10],[15,18]] +//解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. +// +// +// 示例 2: +// +// +//输入:intervals = [[1,4],[4,5]] +//输出:[[1,5]] +//解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。 +// +// +// +// 提示: +// +// +// 1 <= intervals.length <= 10⁴ +// intervals[i].length == 2 +// 0 <= starti <= endi <= 10⁴ +// +// +// Related Topics 数组 排序 👍 2225 👎 0 + + +package Top100Liked.leetcode.editor.cn; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +public class MergeIntervals { + public static void main(String[] args) { + Solution solution = new MergeIntervals().new Solution(); + System.out.println(Arrays.deepToString(solution.merge(new int[][]{{1, 3}, {2, 6}, {8, 10}, {15, 18}}))); + } + + //leetcode submit region begin(Prohibit modification and deletion) + class Solution { + public int[][] merge(int[][] intervals) { + int len = intervals.length; + if (0 == len) { + return intervals; + } else if (1 == len) { + return intervals; + } + Arrays.sort(intervals, Comparator.comparingInt(o -> o[0])); + List res = new ArrayList<>(); + res.add(intervals[0]); + for (int i = 1; i < intervals.length; i++) { + int[] curIntervals = intervals[i], lastIntervals = res.getLast(); + if (curIntervals[0] > lastIntervals[1]) { + res.add(intervals[i]); + } else { + lastIntervals[1] = Math.max(curIntervals[1], lastIntervals[1]); + } + + } + return res.toArray(int[][]::new); + } + } +//leetcode submit region end(Prohibit modification and deletion) + +} \ No newline at end of file diff --git a/src/Top100Liked/leetcode/editor/cn/MinimumWindowSubstring.java b/src/Top100Liked/leetcode/editor/cn/MinimumWindowSubstring.java new file mode 100644 index 0000000..8ce9ce0 --- /dev/null +++ b/src/Top100Liked/leetcode/editor/cn/MinimumWindowSubstring.java @@ -0,0 +1,92 @@ +//给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。 +// +// +// +// 注意: +// +// +// 对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。 +// 如果 s 中存在这样的子串,我们保证它是唯一的答案。 +// +// +// +// +// 示例 1: +// +// +//输入:s = "ADOBECODEBANC", t = "ABC" +//输出:"BANC" +//解释:最小覆盖子串 "BANC" 包含来自字符串 t 的 'A'、'B' 和 'C'。 +// +// +// 示例 2: +// +// +//输入:s = "a", t = "a" +//输出:"a" +//解释:整个字符串 s 是最小覆盖子串。 +// +// +// 示例 3: +// +// +//输入: s = "a", t = "aa" +//输出: "" +//解释: t 中两个字符 'a' 均应包含在 s 的子串中, +//因此没有符合条件的子字符串,返回空字符串。 +// +// +// +// 提示: +// +// +// m == s.length +// n == t.length +// 1 <= m, n <= 10⁵ +// s 和 t 由英文字母组成 +// +// +// +//进阶:你能设计一个在 +//o(m+n) 时间内解决此问题的算法吗? +// +// Related Topics 哈希表 字符串 滑动窗口 👍 2812 👎 0 + + +//package Top100Liked.leetcode.editor.cn; +// +//import java.util.HashMap; +//import java.util.Map; +// +//public class MinimumWindowSubstring { +// public static void main(String[] args) { +// Solution solution = new MinimumWindowSubstring().new Solution(); +// } +// +// //leetcode submit region begin(Prohibit modification and deletion) +// class Solution { +// public String minWindow(String s, String t) { +// int sLen = s.length(), tLen = t.length(); +// char[] sCharArray = s.toCharArray(), tCharArray = t.toCharArray(); +// if (sLen < tLen) { +// return ""; +// } else if (tLen == sLen) { +// if (s.equals(t)) { +// return t; +// } else { +// return ""; +// } +// } +// int needCnt = t.length(), right = 0, left = 0; +// Map needMap = new HashMap<>(); +// for (int i = 0; i < sCharArray.length; i++) { +// while (needCnt > 0) { +// if() +// right++; +// } +// } +// } +// } +////leetcode submit region end(Prohibit modification and deletion) +// +//} \ No newline at end of file diff --git a/src/Top100Liked/leetcode/editor/cn/RotateArray.java b/src/Top100Liked/leetcode/editor/cn/RotateArray.java new file mode 100644 index 0000000..0b67cab --- /dev/null +++ b/src/Top100Liked/leetcode/editor/cn/RotateArray.java @@ -0,0 +1,81 @@ +//给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。 +// +// +// +// 示例 1: +// +// +//输入: nums = [1,2,3,4,5,6,7], k = 3 +//输出: [5,6,7,1,2,3,4] +//解释: +//向右轮转 1 步: [7,1,2,3,4,5,6] +//向右轮转 2 步: [6,7,1,2,3,4,5] +//向右轮转 3 步: [5,6,7,1,2,3,4] +// +// +// 示例 2: +// +// +//输入:nums = [-1,-100,3,99], k = 2 +//输出:[3,99,-1,-100] +//解释: +//向右轮转 1 步: [99,-1,-100,3] +//向右轮转 2 步: [3,99,-1,-100] +// +// +// +// 提示: +// +// +// 1 <= nums.length <= 10⁵ +// -2³¹ <= nums[i] <= 2³¹ - 1 +// 0 <= k <= 10⁵ +// +// +// +// +// 进阶: +// +// +// 尽可能想出更多的解决方案,至少有 三种 不同的方法可以解决这个问题。 +// 你可以使用空间复杂度为 O(1) 的 原地 算法解决这个问题吗? +// +// +// Related Topics 数组 数学 双指针 👍 2084 👎 0 + + +package Top100Liked.leetcode.editor.cn; + +import java.util.Arrays; + +public class RotateArray { + public static void main(String[] args) { + Solution solution = new RotateArray().new Solution(); + int[] nums = {1, 2, 3, 4, 5, 6, 7}; + solution.rotate(nums, 3); + System.out.println(Arrays.toString(nums)); + } + + //leetcode submit region begin(Prohibit modification and deletion) + class Solution { + + public static void reverse(int[] nums, int left, int right) { + while (left < right) { + int temp = nums[left]; + nums[left] = nums[right]; + nums[right] = temp; + left++; + right--; + } + } + + public void rotate(int[] nums, int k) { + k %= nums.length; + reverse(nums, 0, nums.length - 1); + reverse(nums, 0, k - 1); + reverse(nums, k, nums.length - 1); + } + } +//leetcode submit region end(Prohibit modification and deletion) + +} \ No newline at end of file diff --git a/src/Top100Liked/leetcode/editor/cn/SlidingWindowMaximum.java b/src/Top100Liked/leetcode/editor/cn/SlidingWindowMaximum.java new file mode 100644 index 0000000..4553137 --- /dev/null +++ b/src/Top100Liked/leetcode/editor/cn/SlidingWindowMaximum.java @@ -0,0 +1,86 @@ +//给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位 +//。 +// +// 返回 滑动窗口中的最大值 。 +// +// +// +// 示例 1: +// +// +//输入:nums = [1,3,-1,-3,5,3,6,7], k = 3 +//输出:[3,3,5,5,6,7] +//解释: +//滑动窗口的位置 最大值 +//--------------- ----- +//[1 3 -1] -3 5 3 6 7 3 +// 1 [3 -1 -3] 5 3 6 7 3 +// 1 3 [-1 -3 5] 3 6 7 5 +// 1 3 -1 [-3 5 3] 6 7 5 +// 1 3 -1 -3 [5 3 6] 7 6 +// 1 3 -1 -3 5 [3 6 7] 7 +// +// +// 示例 2: +// +// +//输入:nums = [1], k = 1 +//输出:[1] +// +// +// +// +// 提示: +// +// +// 1 <= nums.length <= 10⁵ +// -10⁴ <= nums[i] <= 10⁴ +// 1 <= k <= nums.length +// +// +// Related Topics 队列 数组 滑动窗口 单调队列 堆(优先队列) 👍 2676 👎 0 + + +package Top100Liked.leetcode.editor.cn; + +import java.util.ArrayDeque; +import java.util.Arrays; + +public class SlidingWindowMaximum { + public static void main(String[] args) { + Solution solution = new SlidingWindowMaximum().new Solution(); + System.out.println(Arrays.toString(solution.maxSlidingWindow(new int[]{1, 3, -1, -3, 5, 3, 6, 7}, 3))); + } + + //leetcode submit region begin(Prohibit modification and deletion) + class Solution { + public int[] maxSlidingWindow(int[] nums, int k) { + int length = nums.length; + if (1 == length) { + return nums; + } else if (0 == length) { + return new int[0]; + } + int[] res = new int[nums.length - k + 1]; + ArrayDeque deque = new ArrayDeque<>(); + for (int right = 0; right < length; right++) { + while (!deque.isEmpty() && nums[deque.getLast()] <= nums[right]) { + deque.removeLast(); + } + deque.addLast(right); + int left = right - k + 1; + if (deque.getFirst() < left) { + deque.removeFirst(); + } + if (right + 1 >= k) { + res[left] = nums[deque.getFirst()]; + + } + + } + return res; + } + } +//leetcode submit region end(Prohibit modification and deletion) + +} \ No newline at end of file diff --git a/src/Top100Liked/leetcode/editor/cn/SubarraySumEqualsK.java b/src/Top100Liked/leetcode/editor/cn/SubarraySumEqualsK.java index 66f224e..0d7d8b3 100644 --- a/src/Top100Liked/leetcode/editor/cn/SubarraySumEqualsK.java +++ b/src/Top100Liked/leetcode/editor/cn/SubarraySumEqualsK.java @@ -30,17 +30,35 @@ // // Related Topics 数组 哈希表 前缀和 👍 2235 👎 0 -// package Top100Liked.leetcode.editor.cn; -// public class SubarraySumEqualsK{ -// public static void main(String[] args) { -// Solution solution = new SubarraySumEqualsK().new Solution(); -// } -// //leetcode submit region begin(Prohibit modification and deletion) -// class Solution { -// public int subarraySum(int[] nums, int k) { -// -// } -// } -//// leetcode submit region end(Prohibit modification and deletion) -// -// } +package Top100Liked.leetcode.editor.cn; + +import java.util.HashMap; + +public class SubarraySumEqualsK { + public static void main(String[] args) { + Solution solution = new SubarraySumEqualsK().new Solution(); + System.out.println(solution.subarraySum(new int[]{1, 2, 3}, 3)); + } + + //leetcode submit region begin(Prohibit modification and deletion) + class Solution { + public int subarraySum(int[] nums, int k) { + int result = 0, length = nums.length, preSum = 0; + if (length == 0) { + return result; + } + HashMap hashMap = new HashMap<>(); + hashMap.put(0, 1); + for (int num : nums) { + preSum += num; + if (hashMap.containsKey(preSum - k)) { + result += hashMap.get(preSum - k); + } + hashMap.put(preSum, hashMap.getOrDefault(preSum, 0) + 1); + } + return result; + } + } +// leetcode submit region end(Prohibit modification and deletion) + +} diff --git a/src/Top100Liked/leetcode/editor/cn/doc/content/MaximumSubarray.md b/src/Top100Liked/leetcode/editor/cn/doc/content/MaximumSubarray.md new file mode 100644 index 0000000..a70dbc3 --- /dev/null +++ b/src/Top100Liked/leetcode/editor/cn/doc/content/MaximumSubarray.md @@ -0,0 +1,42 @@ +

给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

+ +

子数组 是数组中的一个连续部分。

+ +

 

+ +

示例 1:

+ +
+输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
+输出:6
+解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
+
+ +

示例 2:

+ +
+输入:nums = [1]
+输出:1
+
+ +

示例 3:

+ +
+输入:nums = [5,4,-1,7,8]
+输出:23
+
+ +

 

+ +

提示:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
+ +

 

+ +

进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。

+ +
Related Topics
  • 数组
  • 分治
  • 动态规划

  • 👍 6532
  • 👎 0
  • \ No newline at end of file diff --git a/src/Top100Liked/leetcode/editor/cn/doc/content/MergeIntervals.md b/src/Top100Liked/leetcode/editor/cn/doc/content/MergeIntervals.md new file mode 100644 index 0000000..8dcaefb --- /dev/null +++ b/src/Top100Liked/leetcode/editor/cn/doc/content/MergeIntervals.md @@ -0,0 +1,30 @@ +

    以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。

    + +

     

    + +

    示例 1:

    + +
    +输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
    +输出:[[1,6],[8,10],[15,18]]
    +解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
    +
    + +

    示例 2:

    + +
    +输入:intervals = [[1,4],[4,5]]
    +输出:[[1,5]]
    +解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= intervals.length <= 104
    • +
    • intervals[i].length == 2
    • +
    • 0 <= starti <= endi <= 104
    • +
    + +
    Related Topics
  • 数组
  • 排序

  • 👍 2225
  • 👎 0
  • \ No newline at end of file diff --git a/src/Top100Liked/leetcode/editor/cn/doc/content/MinimumWindowSubstring.md b/src/Top100Liked/leetcode/editor/cn/doc/content/MinimumWindowSubstring.md new file mode 100644 index 0000000..183d68e --- /dev/null +++ b/src/Top100Liked/leetcode/editor/cn/doc/content/MinimumWindowSubstring.md @@ -0,0 +1,53 @@ +

    给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 ""

    + +

     

    + +

    注意:

    + +
      +
    • 对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
    • +
    • 如果 s 中存在这样的子串,我们保证它是唯一的答案。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:s = "ADOBECODEBANC", t = "ABC"
    +输出:"BANC"
    +解释:最小覆盖子串 "BANC" 包含来自字符串 t 的 'A'、'B' 和 'C'。
    +
    + +

    示例 2:

    + +
    +输入:s = "a", t = "a"
    +输出:"a"
    +解释:整个字符串 s 是最小覆盖子串。
    +
    + +

    示例 3:

    + +
    +输入: s = "a", t = "aa"
    +输出: ""
    +解释: t 中两个字符 'a' 均应包含在 s 的子串中,
    +因此没有符合条件的子字符串,返回空字符串。
    + +

     

    + +

    提示:

    + +
      +
    • m == s.length
    • +
    • n == t.length
    • +
    • 1 <= m, n <= 105
    • +
    • st 由英文字母组成
    • +
    + +

     

    +进阶:你能设计一个在 +o(m+n) 时间内解决此问题的算法吗? + +
    Related Topics
  • 哈希表
  • 字符串
  • 滑动窗口

  • 👍 2812
  • 👎 0
  • \ No newline at end of file diff --git a/src/Top100Liked/leetcode/editor/cn/doc/content/RotateArray.md b/src/Top100Liked/leetcode/editor/cn/doc/content/RotateArray.md new file mode 100644 index 0000000..9c612e1 --- /dev/null +++ b/src/Top100Liked/leetcode/editor/cn/doc/content/RotateArray.md @@ -0,0 +1,44 @@ +

    给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。

    + +

     

    + +

    示例 1:

    + +
    +输入: nums = [1,2,3,4,5,6,7], k = 3
    +输出: [5,6,7,1,2,3,4]
    +解释:
    +向右轮转 1 步: [7,1,2,3,4,5,6]
    +向右轮转 2 步: [6,7,1,2,3,4,5]
    +向右轮转 3 步: [5,6,7,1,2,3,4]
    +
    + +

    示例 2:

    + +
    +输入:nums = [-1,-100,3,99], k = 2
    +输出:[3,99,-1,-100]
    +解释: 
    +向右轮转 1 步: [99,-1,-100,3]
    +向右轮转 2 步: [3,99,-1,-100]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • -231 <= nums[i] <= 231 - 1
    • +
    • 0 <= k <= 105
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 尽可能想出更多的解决方案,至少有 三种 不同的方法可以解决这个问题。
    • +
    • 你可以使用空间复杂度为 O(1) 的 原地 算法解决这个问题吗?
    • +
    + +
    Related Topics
  • 数组
  • 数学
  • 双指针

  • 👍 2084
  • 👎 0
  • \ No newline at end of file diff --git a/src/Top100Liked/leetcode/editor/cn/doc/content/SlidingWindowMaximum.md b/src/Top100Liked/leetcode/editor/cn/doc/content/SlidingWindowMaximum.md new file mode 100644 index 0000000..b4ef3fe --- /dev/null +++ b/src/Top100Liked/leetcode/editor/cn/doc/content/SlidingWindowMaximum.md @@ -0,0 +1,40 @@ +

    给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

    + +

    返回 滑动窗口中的最大值

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
    +输出:[3,3,5,5,6,7]
    +解释:
    +滑动窗口的位置                最大值
    +---------------               -----
    +[1  3  -1] -3  5  3  6  7       3
    + 1 [3  -1  -3] 5  3  6  7       3
    + 1  3 [-1  -3  5] 3  6  7       5
    + 1  3  -1 [-3  5  3] 6  7       5
    + 1  3  -1  -3 [5  3  6] 7       6
    + 1  3  -1  -3  5 [3  6  7]      7
    +
    + +

    示例 2:

    + +
    +输入:nums = [1], k = 1
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • -104 <= nums[i] <= 104
    • +
    • 1 <= k <= nums.length
    • +
    + +
    Related Topics
  • 队列
  • 数组
  • 滑动窗口
  • 单调队列
  • 堆(优先队列)

  • 👍 2676
  • 👎 0
  • \ No newline at end of file