From 591d8a651b91183319ea40899073e80be1a53b02 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Fri, 22 Apr 2022 01:04:05 +0200 Subject: [PATCH 01/42] Create DistributeCandiesToPeople.java --- .../DistributeCandiesToPeople.java | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java diff --git a/algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java b/algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java new file mode 100644 index 00000000..9565711c --- /dev/null +++ b/algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java @@ -0,0 +1,79 @@ +/***************************************************************************************************** + * + * We distribute some number of candies, to a row of n = num_people people in the + * following way: + * + * We then give 1 candy to the first person, 2 candies to the second person, and so on until + * we give n candies to the last person. + * + * Then, we go back to the start of the row, giving n + 1 candies to the first person, n + + * 2 candies to the second person, and so on until we give 2 * n candies to the last + * person. + * + * This process repeats (with us giving one more candy each time, and moving to the start of + * the row after we reach the end) until we run out of candies. The last person will receive all + * of our remaining candies (not necessarily one more than the previous gift). + * + * Return an array (of length num_people and sum candies) that represents the final + * distribution of candies. + * + * + * Example 1: + * + * Input: candies = 7, num_people = 4 + * Output: [1,2,3,1] + * Explanation: + * On the first turn, ans[0] += 1, and the array is [1,0,0,0]. + * On the second turn, ans[1] += 2, and the array is [1,2,0,0]. + * On the third turn, ans[2] += 3, and the array is [1,2,3,0]. + * On the fourth turn, ans[3] += 1 (because there is only one candy + * left), and the final array is [1,2,3,1]. + * + * Example 2: + * + * Input: candies = 10, num_people = 3 + * Output: [5,2,3] + * Explanation: + * On the first turn, ans[0] += 1, and the array is [1,0,0]. + * On the second turn, ans[1] += 2, and the array is [1,2,0]. + * On the third turn, ans[2] += 3, and the array is [1,2,3]. + * On the fourth turn, ans[0] += 4, and the final array is [5,2,3]. + * + * + * Constraints: + * + * 1 <= candies <= 10^9 + * 1 <= num_people <= 1000 + * + * Explanation of the solution: + * + * 1. While we have given less candies than the ones we had at the beginning (while(total < candies){...}) + * + * 2. Use count % num_people == 0 to determine the current index of the people. + ******************************************************************************************************/ + +class Solution { + public int[] distributeCandies(int candies, int num_people) { + int[] res = new int[num_people]; //Initialize the array of people + int toGiveCandie = 1, count = 0, total = 0; + while(total < candies){ //While the total candies given is fewer than the candies we have... + if(count % num_people == 0){ //This is to 'reset' de counter to 0 when we reach the last person. + count = 0; + } + if(total + toGiveCandie <= candies){ + //If the number of candies we have already given plus the candies we are + // going to give are less or equal than the total candies... + res[count] += toGiveCandie; //We add the candies to the array (give the candie to the person) + total += toGiveCandie; //We update the candies we have given + toGiveCandie++; //To the next person we will give one more candie + }else{ + //If we don't have the enough candies, we just give the candies left + res[count] += candies-total; + total += candies-total; + toGiveCandie++; + } + count++; + } + return res; //We return the filled array + } +} From 0c35e3e403221db77cf27a0fabc7c256372a6003 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Fri, 22 Apr 2022 01:08:58 +0200 Subject: [PATCH 02/42] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2bf93af3..2771b104 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ LeetCode |1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/) | [C++](./algorithms/cpp/filterRestaurantsByVeganFriendlyPriceAndDistance/FilterRestaurantsByVeganFriendlyPriceAndDistance.cpp)|Medium| |1207|[Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C++](./algorithms/cpp/uniqueNumberOfOccurrences/Unique-Number-of-Occurrences.cpp)|Easy| |1170|[Compare Strings by Frequency of the Smallest Character](https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/) | [C++](./algorithms/cpp/compareStringsByFrequencyOfTheSmallestCharacter/CompareStringsByFrequencyOfTheSmallestCharacter.cpp)|Easy| +|1103|[Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people/) | [Java](./algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java)|Easy| |1071|[Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings/) | [C++](./algorithms/cpp/greatestCommonDivisorOfStrings/GreatestCommonDivisorOfStrings.cpp)|Easy| |1030|[Matrix Cells in Distance Order](https://leetcode.com/problems/matrix-cells-in-distance-order/) | [C++](./algorithms/cpp/matrixCellsInDistanceOrder/MatrixCellsInDistanceOrder.cpp)|Easy| |1029|[Two City Scheduling](https://leetcode.com/problems/two-city-scheduling/) | [C++](./algorithms/cpp/twoCityScheduling/TwoCityScheduling.cpp)|Easy| From bc6ae555835e5dc39216ea7ed70362904d24b38b Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Fri, 22 Apr 2022 01:21:42 +0200 Subject: [PATCH 03/42] Create IsSubsequence.java --- .../java/src/IsSubsequence/IsSubsequence.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 algorithms/java/src/IsSubsequence/IsSubsequence.java diff --git a/algorithms/java/src/IsSubsequence/IsSubsequence.java b/algorithms/java/src/IsSubsequence/IsSubsequence.java new file mode 100644 index 00000000..bc494c52 --- /dev/null +++ b/algorithms/java/src/IsSubsequence/IsSubsequence.java @@ -0,0 +1,56 @@ +/***************************************************************************************************** + * + * Given two strings s and t, return true if s is a subsequence of t, or false otherwise. + * + * A subsequence of a string is a new string that is formed from the original string by + * deleting some (can be none) of the characters without disturbing the relative positions of + * the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). + * + * Example 1: + * + * Input: s = "abc", t = "ahbgdc" + * Output: true + * + * Example 2: + * + * Input: s = "axc", t = "ahbgdc" + * Output: false + * + * Constraints: + * + * 0 <= s.length <= 100 + * 0 <= t.length <= 10^4 + * s and t consist only of lowercase English letters. + * + * + * Explanation of the solution: + * + * Firstly we analyze de string 's' char by char, the string 't' is required to contain + * the analized char in order to return true. If 't' does not contains the char, we return false. + * + * Secondly, if 't' contains the char we delete all the letters in 't' until the position of the + * char we have just analized (including the char, that is why we have add the 1 at the t.substring( )) + * and we can also delete from 's' the recently analized char. + * + * Finally, after deleting all the unwanted letters in 't' and 's', if the length of 's' is bigger + * than the length of 't' it means that the string 's' have more chars left to analize than the amount of + * chars 't' contains, as a result we return false. + * + * This is an example of the code: + ******************************************************************************************************/ + +class Solution { + public boolean isSubsequence(String s, String t) { //The explanation is above + for(char i : s.toCharArray()){ + if(!t.contains(String.valueOf(i))){ + return false; + } + t = t.substring(t.indexOf(i)+1); + s = s.substring(1); + if(s.length() > t.length()){ + return false; + } + } + return true; + } +} From 6dcac29f1307fbcb2ad21d7692d57bf22407ec8e Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Fri, 22 Apr 2022 01:24:41 +0200 Subject: [PATCH 04/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2771b104..fda6fdf9 100644 --- a/README.md +++ b/README.md @@ -261,7 +261,7 @@ LeetCode |395|[Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp)|Medium| |394|[Decode String](https://leetcode.com/problems/decode-string/) | [C++](./algorithms/cpp/decodeString/DecodeString.cpp)|Medium| |393|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./algorithms/cpp/UTF8Validation/UTF8Validation.cpp)|Medium| -|392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp)|Medium| +|392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp),[Java](./algorithms/java/src/IsSubsequence/IsSubsequence.java)|Easy| |391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./algorithms/cpp/perfectRectangle/PerfectRectangle.cpp)|Hard| |390|[Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./algorithms/cpp/eliminationGame/EliminationGame.cpp)|Medium| |389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./algorithms/cpp/findTheDifference/FindTheDifference.cpp)|Easy| From 4c6f6a0f9510bd3d5fd6e132464f145ee4744008 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Fri, 22 Apr 2022 01:26:35 +0200 Subject: [PATCH 05/42] Update IsSubsequence.java --- algorithms/java/src/IsSubsequence/IsSubsequence.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/algorithms/java/src/IsSubsequence/IsSubsequence.java b/algorithms/java/src/IsSubsequence/IsSubsequence.java index bc494c52..6432a545 100644 --- a/algorithms/java/src/IsSubsequence/IsSubsequence.java +++ b/algorithms/java/src/IsSubsequence/IsSubsequence.java @@ -1,3 +1,7 @@ +// Source : https://leetcode.com/problems/is-subsequence/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 22-04-2022 + /***************************************************************************************************** * * Given two strings s and t, return true if s is a subsequence of t, or false otherwise. From 382e4f586a638c3c060488eedce2c5c40faa8c27 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Fri, 22 Apr 2022 01:27:52 +0200 Subject: [PATCH 06/42] Update DistributeCandiesToPeople.java --- .../DistributeCandiesToPeople/DistributeCandiesToPeople.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java b/algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java index 9565711c..f2150728 100644 --- a/algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java +++ b/algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java @@ -1,3 +1,7 @@ +// Source : https://leetcode.com/problems/distribute-candies-to-people/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 22-04-2022 + /***************************************************************************************************** * * We distribute some number of candies, to a row of n = num_people people in the From c2c009167d4e0a2d4175384a1f61732209923a8b Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 12:50:52 +0200 Subject: [PATCH 07/42] Create MedianOfTwoSortedArrays.java --- .../MedianOfTwoSortedArrays.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 algorithms/java/src/MedianOfTwoSortedArrays/MedianOfTwoSortedArrays.java diff --git a/algorithms/java/src/MedianOfTwoSortedArrays/MedianOfTwoSortedArrays.java b/algorithms/java/src/MedianOfTwoSortedArrays/MedianOfTwoSortedArrays.java new file mode 100644 index 00000000..27580758 --- /dev/null +++ b/algorithms/java/src/MedianOfTwoSortedArrays/MedianOfTwoSortedArrays.java @@ -0,0 +1,57 @@ +// Source : https://leetcode.com/problems/median-of-two-sorted-arrays/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 23-04-2022 + +/***************************************************************************************************** + * + * Given two sorted arrays nums1 and nums2 of size m and n respectively, + * return the median of the two sorted arrays. + * + * The overall run time complexity should be O(log (m+n)). + * + * Example 1: + * + * Input: nums1 = [1,3], nums2 = [2] + * Output: 2.00000 + * Explanation: merged array = [1,2,3] and median is 2. + * + * Example 2: + * + * Input: nums1 = [1,2], nums2 = [3,4] + * Output: 2.50000 + * Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. + * + * + * Constraints: + * + * nums1.length == m + * nums2.length == n + * 0 <= m <= 1000 + * 0 <= n <= 1000 + * 1 <= m + n <= 2000 + * -10^6 <= nums1[i], nums2[i] <= 10^6 + * + * Explanation of the solution: + * + * 1. Concatenate both arrays (int[] concatenate). + * + * 2. Sort the 'concatenate' array. + * + * 3. If 'concatenate' have an odd nuber of elements return the element in the middle, otherwise return the sum of the middle numbers. + ******************************************************************************************************/ + +class Solution { + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + double c; + int[] concatenate = new int[nums1.length + nums2.length]; + System.arraycopy(nums1, 0, concatenate, 0, nums1.length); //Add the first array + System.arraycopy(nums2, 0, concatenate, nums1.length, nums2.length); //Add the second array + Arrays.sort(concatenate); + if (concatenate.length % 2 == 0){ + c = concatenate[concatenate.length/2-1]+concatenate[concatenate.length/2]; + return c/2; + }else { + return concatenate[concatenate.length/2]; + } + } +} From 7a1528c97d1be221d863b313fe681cdd96dfe5d8 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 12:53:57 +0200 Subject: [PATCH 08/42] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fda6fdf9..ef47e780 100644 --- a/README.md +++ b/README.md @@ -261,7 +261,7 @@ LeetCode |395|[Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp)|Medium| |394|[Decode String](https://leetcode.com/problems/decode-string/) | [C++](./algorithms/cpp/decodeString/DecodeString.cpp)|Medium| |393|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./algorithms/cpp/UTF8Validation/UTF8Validation.cpp)|Medium| -|392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp),[Java](./algorithms/java/src/IsSubsequence/IsSubsequence.java)|Easy| +|392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp), [Java](./algorithms/java/src/IsSubsequence/IsSubsequence.java)|Easy| |391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./algorithms/cpp/perfectRectangle/PerfectRectangle.cpp)|Hard| |390|[Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./algorithms/cpp/eliminationGame/EliminationGame.cpp)|Medium| |389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./algorithms/cpp/findTheDifference/FindTheDifference.cpp)|Easy| @@ -559,7 +559,7 @@ LeetCode |7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/)| [C++](./algorithms/cpp/reverseInteger/reverseInteger.cpp)|Easy| |6|[ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)| [C++](./algorithms/cpp/zigZagConversion/zigZagConversion.cpp)|Easy| |5|[Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)| [C++](./algorithms/cpp/longestPalindromicSubstring/longestPalindromicSubstring.cpp)|Medium| -|4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)| [C++](./algorithms/cpp/medianOfTwoSortedArrays/medianOfTwoSortedArrays.cpp)|Hard| +|4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)| [C++](./algorithms/cpp/medianOfTwoSortedArrays/medianOfTwoSortedArrays.cpp), [Java](./algorithms/java/src/MedianOfTwoSortedArrays/MedianOfTwoSortedArrays.java)|Hard| |3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| [C++](./algorithms/cpp/longestSubstringWithoutRepeatingCharacters/longestSubstringWithoutRepeatingCharacters.cpp)|Medium| |2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)| [C++](./algorithms/cpp/addTwoNumbers/addTwoNumbers.cpp)|Medium| |1|[Two Sum](https://leetcode.com/problems/two-sum/)| [C++](./algorithms/cpp/twoSum/twoSum.cpp), [Go](./algorithms/golang/twoSum/twoSum.go)|Easy| From 42024b4cf5c5644851e18b04d9f56b963acc520e Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 13:23:29 +0200 Subject: [PATCH 09/42] Create IntegerToRoman.java --- .../src/IntegerToRoman/IntegerToRoman.java | 140 ++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 algorithms/java/src/IntegerToRoman/IntegerToRoman.java diff --git a/algorithms/java/src/IntegerToRoman/IntegerToRoman.java b/algorithms/java/src/IntegerToRoman/IntegerToRoman.java new file mode 100644 index 00000000..9922b50a --- /dev/null +++ b/algorithms/java/src/IntegerToRoman/IntegerToRoman.java @@ -0,0 +1,140 @@ +// Source : https://leetcode.com/problems/integer-to-roman/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 23-04-2022 + +/***************************************************************************************************** + * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. + * + * Symbol Value + * I 1 + * V 5 + * X 10 + * L 50 + * C 100 + * D 500 + * M 1000 + * + * For example, 2 is written as II in Roman numeral, just two one's added + * together. 12 is written as XII, which is simply X + II. The number 27 is + * written as XXVII, which is XX + V + II. + * + * Roman numerals are usually written largest to smallest from left to right. + * However, the numeral for four is not IIII. Instead, the number four is + * written as IV. Because the one is before the five we subtract it making four. + * The same principle applies to the number nine, which is written as IX. There + * are six instances where subtraction is used: + * + * I can be placed before V (5) and X (10) to make 4 and 9. + * X can be placed before L (50) and C (100) to make 40 and 90. + * C can be placed before D (500) and M (1000) to make 400 and 900. + * + * Given an integer, convert it to a roman numeral. + * + * Example 1: + * + * Input: num = 3 + * Output: "III" + * Explanation: 3 is represented as 3 ones. + * + * Example 2: + * + * Input: num = 58 + * Output: "LVIII" + * Explanation: L = 50, V = 5, III = 3. + * + * Example 3: + * + * Input: num = 1994 + * Output: "MCMXCIV" + * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. + * + * Constraints: + * + * 1 <= num <= 3999 + * + * Explanation of the solution: + * + * We start looking if the number given is bigger than 1000 + * to see if there is going to be a letter 'M' (1000) in the solution. + * + * If the number > 1000 we repeat the process until a maximun of three 'M' + * substracting 1000 to the number each time. + * + * The process is the same for all the letters. + * + * We also analyze special cases such as 'CM' (num < 1000 && num > 899), 'CD' (num < 500 && num > 399), + * 'XC' (num < 100 && num > 89), 'XL' (num < 50 && num > 39), 'IX' (num == 9) and 'IV' (num == 4). + ******************************************************************************************************/ + +class Solution { + public String intToRoman(int num) { + String res = ""; + int cnt = 0; + while(num >= 1000 && cnt < 3){ + res += "M"; + num -= 1000; + cnt++; + } + cnt = 0; + if(num < 1000 && num > 899){ + res += "CM"; + num -= 900; + } + while(num >= 500 && cnt < 3){ + res += "D"; + num -= 500; + cnt++; + } + cnt = 0; + if(num < 500 && num > 399){ + res += "CD"; + num -= 400; + } + while(num >= 100 && cnt < 3){ + res += "C"; + num -= 100; + cnt++; + } + cnt = 0; + if(num < 100 && num > 89){ + res += "XC"; + num -= 90; + } + while(num >= 50 && cnt < 3){ + res += "L"; + num -= 50; + cnt++; + } + cnt = 0; + if(num < 50 && num > 39){ + res += "XL"; + num -= 40; + } + while(num >= 10 && cnt < 3){ + res += "X"; + num -= 10; + cnt++; + } + cnt = 0; + if(num == 9){ + res += "IX"; + num -= 9; + } + while(num >= 5 && cnt < 3){ + res += "V"; + num -= 5; + cnt++; + } + cnt = 0; + if(num == 4){ + res += "IV"; + num -= 4; + } + while(num >= 1 && cnt < 3){ + res += "I"; + num -= 1; + cnt++; + } + return res; + } +} From 5baf8fd08e08d9dea2a4232f6aac207dae6185d9 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 13:29:46 +0200 Subject: [PATCH 10/42] Create RomanToInteger.java --- .../src/RomanToInteger/RomanToInteger.java | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 algorithms/java/src/RomanToInteger/RomanToInteger.java diff --git a/algorithms/java/src/RomanToInteger/RomanToInteger.java b/algorithms/java/src/RomanToInteger/RomanToInteger.java new file mode 100644 index 00000000..e6e09e7a --- /dev/null +++ b/algorithms/java/src/RomanToInteger/RomanToInteger.java @@ -0,0 +1,120 @@ +// Source : https://leetcode.com/problems/roman-to-integer/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 23-04-2022 + +/***************************************************************************************************** + * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. + * + * Symbol Value + * I 1 + * V 5 + * X 10 + * L 50 + * C 100 + * D 500 + * M 1000 + * + * For example, 2 is written as II in Roman numeral, just two one's added + * together. 12 is written as XII, which is simply X + II. The number 27 is + * written as XXVII, which is XX + V + II. + * + * Roman numerals are usually written largest to smallest from left to right. + * However, the numeral for four is not IIII. Instead, the number four is + * written as IV. Because the one is before the five we subtract it making four. + * The same principle applies to the number nine, which is written as IX. There + * are six instances where subtraction is used: + * + * I can be placed before V (5) and X (10) to make 4 and 9. + * X can be placed before L (50) and C (100) to make 40 and 90. + * C can be placed before D (500) and M (1000) to make 400 and 900. + * + * Given an integer, convert it to a roman numeral. + * + * Example 1: + * + * Input: s = "III" + * Output: 3 + * Explanation: III = 3. + * + * Example 2: + * + * Input: s = "LVIII" + * Output: 58 + * Explanation: L = 50, V= 5, III = 3. + * + * Example 3: + * + * Input: s = "MCMXCIV" + * Output: 1994 + * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. + * + * Constraints: + * + * 1 <= s.length <= 15 + * s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). + * It is guaranteed that s is a valid roman numeral in the range [1, 3999]. + * + * Explanation of the solution: + * + * Letters 'V' ,'L', 'D' and 'M' can't be subtracted so when they are readed we can just add their values. + * + * In contrast, the letter 'I' can be subtracted at 4 and 9... Example: IV = 4, IX = 9. + * If the letter 'I' is at the end of the number, we just add it's value. + * + * Letter 'X' can be subtracted at 40 and 90... Example: XL = 40, XC = 90. + * + * Letter 'C' can be subtracted at 400 and 900... Example: CD = 400, CM = 900. + * + * I used an array to store the values, but you could perfectly just write the values of it's letters. + * + * While reading the next letter you should check that it's not the last one, I used "if( i != s.length()-1 && ... )" + ******************************************************************************************************/ + +class Solution { + public int romanToInt(String s) { + int[] nums = {1,5,10,50,100,500,1000}; + int res = 0; + for(int i = 0; i < s.length(); i++){ + if(s.charAt(i) == 'I'){ + if(i != s.length()-1 && s.charAt(i+1) == 'V'){ + res += nums[1]-nums[0]; + i++; + }else if(i != s.length()-1 && s.charAt(i+1) == 'X'){ + res += nums[2]-nums[0]; + i++; + }else{ + res += nums[0]; + } + }else if(s.charAt(i) == 'V'){ + res += nums[1]; + }else if(s.charAt(i) == 'X'){ + if(i != s.length()-1 && s.charAt(i+1) == 'C'){ + res += nums[4]-nums[2]; + i++; + }else if(i != s.length()-1 && s.charAt(i+1) == 'L'){ + res += nums[3]-nums[2]; + i++; + }else{ + res += nums[2]; + } + }else if(s.charAt(i) == 'L' ){ + res += nums[3]; + }else if(s.charAt(i) == 'C'){ + if(i != s.length()-1 && s.charAt(i+1) == 'D'){ + res += nums[5]-nums[4]; + i++; + }else if(i != s.length()-1 && s.charAt(i+1) == 'M'){ + res += nums[6]-nums[4]; + i++; + }else{ + res += nums[4]; + } + }else if(s.charAt(i) == 'D'){ + res += nums[5]; + }else if(s.charAt(i) == 'M'){ + res += nums[6]; + } + } + return res; + } +} From 3ae05eedc25979d4515b32b4c334986cafd10f2d Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 13:32:21 +0200 Subject: [PATCH 11/42] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ef47e780..5004f8ab 100644 --- a/README.md +++ b/README.md @@ -550,8 +550,8 @@ LeetCode |16|[3Sum Closest](https://leetcode.com/problems/3sum-closest/)| [C++](./algorithms/cpp/3SumClosest/3SumClosest.cpp)|Medium| |15|[3Sum](https://leetcode.com/problems/3sum/)| [C++](./algorithms/cpp/3Sum/3Sum.cpp)|Medium| |14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [C++](./algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp)|Easy| -|13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [C++](./algorithms/cpp/romanToInteger/romanToInteger.cpp)|Easy| -|12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman/)| [C++](./algorithms/cpp/integerToRoman/integerToRoman.cpp)|Medium| +|13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [C++](./algorithms/cpp/romanToInteger/romanToInteger.cpp), [Java](./algorithms/java/src/RomanToInteger/RomanToInteger.java)|Easy| +|12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman/)| [C++](./algorithms/cpp/integerToRoman/integerToRoman.cpp), [Java](./algorithms/java/src/IntegerToRoman/IntegerToRoman.java)|Medium| |11|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [C++](./algorithms/cpp/containerWithMostWater/containerWithMostWater.cpp), [Java](./algorithms/java/src/containerwithmostwater.java)|Medium| |10|[Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/)| [C++](./algorithms/cpp/regularExpressionMatching/regularExpressionMatching.cpp)|Hard| |9|[Palindrome Number](https://leetcode.com/problems/palindrome-number/)| [C++](./algorithms/cpp/palindromeNumber/palindromeNumber.cpp), [Java](./algorithms/java/src/palindromeNumber/PalindromeNumber.java)|Easy| From 9255f1680057027acb1be347e0639f17b2ec5434 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 18:05:41 +0200 Subject: [PATCH 12/42] Create LongestCommonPrefix.java --- .../LongestCommonPrefix.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 algorithms/java/src/LongestCommonPrefix/LongestCommonPrefix.java diff --git a/algorithms/java/src/LongestCommonPrefix/LongestCommonPrefix.java b/algorithms/java/src/LongestCommonPrefix/LongestCommonPrefix.java new file mode 100644 index 00000000..cc79a250 --- /dev/null +++ b/algorithms/java/src/LongestCommonPrefix/LongestCommonPrefix.java @@ -0,0 +1,59 @@ +// Source : https://leetcode.com/problems/longest-common-prefix/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 22-04-2022 + +/***************************************************************************************************** + * Write a function to find the longest common prefix string amongst an array of strings. + * + * If there is no common prefix, return an empty string "". + * + * Example 1: + * + * Input: strs = ["flower","flow","flight"] + * Output: "fl" + * + * Example 2: + * + * Input: strs = ["dog","racecar","car"] + * Output: "" + * Explanation: There is no common prefix among the input strings. + * + * Constraints: + * + * 1 <= strs.length <= 200 + * 0 <= strs[i].length <= 200 + * strs[i] consists of only lower-case English letters. + * + * Explanation of the solution: + * + * 1. Get the first word in the array 'strs'. As all the words in the array are believed to have + * a common prefix, we compare if the other words have the same prefix (using containsPrefix(word, strs)). + * + * 2. If a word in the array does not contain the same prefix we return false, otherwise (if all the words in 'strs' have the same prefix) we return true. + * If 'contains' is true we have found the prefix, in contrast, if 'contains' is false we continue looking + * for the prefix deleting the last character of the word given and using 'containsPrefix()' again. + ******************************************************************************************************/ + +class Solution { + public String longestCommonPrefix(String[] strs) { + String word = strs[0]; + boolean contains; + while(true){ + contains = containsPrefix(word,strs); + if(!contains){ + word = word.substring(0,word.length()-1); //Delete the last character + }else{ + return word; + } + } + } + + public boolean containsPrefix(String word, String[] strs){ + for(String i : strs){ + if(i.indexOf(word) != 0){ //The prefix must be at the beginning of the word + return false; + } + } + return true; + } +} From 47ccb47f1ce1860518d6869dd6cfcef4a31ffdc8 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 18:07:36 +0200 Subject: [PATCH 13/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5004f8ab..4a8da7c2 100644 --- a/README.md +++ b/README.md @@ -549,7 +549,7 @@ LeetCode |17|[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [C++](./algorithms/cpp/letterCombinationsOfAPhoneNumber/letterCombinationsOfAPhoneNumber.cpp)|Medium| |16|[3Sum Closest](https://leetcode.com/problems/3sum-closest/)| [C++](./algorithms/cpp/3SumClosest/3SumClosest.cpp)|Medium| |15|[3Sum](https://leetcode.com/problems/3sum/)| [C++](./algorithms/cpp/3Sum/3Sum.cpp)|Medium| -|14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [C++](./algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp)|Easy| +|14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [C++](./algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp), [Java](./algorithms/java/src/LongestCommonPrefix/LongestCommonPrefix.java)|Easy| |13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [C++](./algorithms/cpp/romanToInteger/romanToInteger.cpp), [Java](./algorithms/java/src/RomanToInteger/RomanToInteger.java)|Easy| |12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman/)| [C++](./algorithms/cpp/integerToRoman/integerToRoman.cpp), [Java](./algorithms/java/src/IntegerToRoman/IntegerToRoman.java)|Medium| |11|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [C++](./algorithms/cpp/containerWithMostWater/containerWithMostWater.cpp), [Java](./algorithms/java/src/containerwithmostwater.java)|Medium| From 7e8e9c18819b685afdbea25f4e5ba8eb32472117 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 20:54:41 +0200 Subject: [PATCH 14/42] Create ValidParentheses.java --- .../ValidParentheses/ValidParentheses.java | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 algorithms/java/src/ValidParentheses/ValidParentheses.java diff --git a/algorithms/java/src/ValidParentheses/ValidParentheses.java b/algorithms/java/src/ValidParentheses/ValidParentheses.java new file mode 100644 index 00000000..827ba042 --- /dev/null +++ b/algorithms/java/src/ValidParentheses/ValidParentheses.java @@ -0,0 +1,91 @@ +// Source : https://leetcode.com/problems/valid-parentheses/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 23-04-2022 + +/********************************************************************************************************* + * Given a string s containing just the characters '(', ')', '{', '}', '[' and ']' + * determine if the input string is valid. + * + * An input string is valid if: + * + * 1. Open brackets must be closed by the same type of brackets. + * + * 2. Open brackets must be closed in the correct order. + * + * Example 1: + * + * Input: s = "()" + * Output: true + * + * Example 2: + * + * Input: s = "()[]{}" + * Output: true + * + * Explanation 3: + * + * Input: s = "(]" + * Output: false + * + * Constraints: + * + * 1 <= s.length <= 10^4 + * s consists of parentheses only '()[]{}'. + * + * Explanation of the solution: + * + * 1. We analyze char by char the string 's' given, if we analyze an opening parentheses we can + * include it in the Stack if the last parentheses added to the Stack was not another opening + * parentheses or if the Stack is empty. + * + * 2. If we analyze a closing parentheses and the last introduced parentheses to the Stack is exactly the + * opening parentheses of the one we are analyzing we eliminate the opening parentheses from the Stack. + * Else we return false. + * + * 3. After having analyzed 's', if the Stack is empty it means all parentheses have being closed so we return + * true, if not, we return false; + *************************************************************************************************************/ + +//I HAVE USED AN IF{}ELSE IF{} COMBINATION BUT YOU COULD HAVE USED A SWITCH{} TO CHECK THE TYPE OF PARENTHESES. +class Solution { + public boolean isValid(String s) { + Stack pila = new Stack(); + for (char i : s.toCharArray()){ + if(i == '('){ + pila.add(i); + }else if(i == ')'){ + if (pila.isEmpty()){ + return false; + }else if (pila.peek().equals('(')){ + pila.pop(); + }else { + return false; + } + }else if(i == '['){ + pila.add(i); + }else if(i == ']'){ + if (pila.isEmpty()){ + return false; + }else if (pila.peek().equals('[')){ + pila.pop(); + }else { + return false; + } + }else if(i == '{'){ + pila.add(i); + }else{ + if (pila.isEmpty()){ + return false; + }else if (pila.peek().equals('{')){ + pila.pop(); + }else { + return false; + } + } + } + if (pila.isEmpty()){ + return true; + } + return false; + } +} From 4c6227af7703479a357bd5001a13548aac4014c5 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 21:31:10 +0200 Subject: [PATCH 15/42] Create RecoverBinarySearchTree.java --- .../RecoverBinarySearchTree.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 algorithms/java/src/RecoverBinarySearchTree/RecoverBinarySearchTree.java diff --git a/algorithms/java/src/RecoverBinarySearchTree/RecoverBinarySearchTree.java b/algorithms/java/src/RecoverBinarySearchTree/RecoverBinarySearchTree.java new file mode 100644 index 00000000..a6deaf4e --- /dev/null +++ b/algorithms/java/src/RecoverBinarySearchTree/RecoverBinarySearchTree.java @@ -0,0 +1,69 @@ +// Source : https://leetcode.com/problems/recover-binary-search-tree/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 23-04-2022 + +/***************************************************************************************************** + * + * You are given the root of a binary search tree (BST), where the values of + * exactly two nodes of the tree were swapped by mistake. Recover the tree + * without changing its structure. + * + * Example 1: + * + * Input: root = [1,3,null,null,2] + * Output: [3,1,null,null,2] + * Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. + * + * Example 2: + * + * Input: root = [3,1,4,null,null,2] + * Output: [2,1,4,null,null,3] + * Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid. + * + * Constraints: + * + * The number of nodes in the tree is in the range [2, 1000]. + * -2^31 <= Node.val <= 2^31 - 1 + * + * Explanation of the solution: + * + * 1. Firstly we apply the 'ordenCentralRec(root, new ArrayList<>(), aux1, aux2)' method to extract the + * nodes of the tree in an ArrayList. We read the tree InOrder traversal. + * Note that both aux1 and aux2 value's is Integer.MIN_VALUE so the nodo.val doesn't change. + * + * 2. We check the values obtained in the ArrayList to see which are the changed numbers. + * + * 3. Finally we apply the 'ordenCentralRec(root, new ArrayList<>(), aux1, aux2)' method to extract the + * final version of the binary search tree HAVING changed aux1 and aux2. The method will change the + * nodes values and return the the binary search tree changed. + ******************************************************************************************************/ + +class Solution { + public void recoverTree(TreeNode root) { + int aux1 = Integer.MIN_VALUE, aux2 = Integer.MIN_VALUE; + List nums = ordenCentralRec(root, new ArrayList<>(), aux1, aux2); + for (int i = 0; i < nums.size()-1;i++){ + if (nums.get(i) > nums.get(i+1)){ + if (aux1 == Integer.MIN_VALUE){ + aux1 = nums.get(i); + } + aux2 = nums.get(i+1); + } + } + nums.clear(); + ordenCentralRec(root, nums, aux1, aux2); + } + private List ordenCentralRec(TreeNode nodo, List nums, int aux1, int aux2) { + if (nodo != null) { + if (aux1 == nodo.val){ + nodo.val = aux2; + }else if (aux2 == nodo.val){ + nodo.val = aux1; + } + nums = ordenCentralRec(nodo.left, nums, aux1, aux2); + nums.add(nodo.val); + nums = ordenCentralRec(nodo.right, nums, aux1, aux2); + } + return nums; + } +} From b1736c734ab4ecb1d52110b11e72fe0c37b261be Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 21:45:29 +0200 Subject: [PATCH 16/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4a8da7c2..b36d331e 100644 --- a/README.md +++ b/README.md @@ -464,7 +464,7 @@ LeetCode |102|[Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [C++](./algorithms/cpp/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.cpp), [Java](./algorithms/java/src/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.java)|Easy| |101|[Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./algorithms/cpp/symmetricTree/symmetricTree.cpp)|Easy| |100|[Same Tree](https://leetcode.com/problems/same-tree/)| [C++](./algorithms/cpp/sameTree/sameTree.cpp)|Easy| -|99|[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)| [C++](./algorithms/cpp/recoverBinarySearchTree/recoverBinarySearchTree.cpp)|Hard| +|99|[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)| [C++](./algorithms/cpp/recoverBinarySearchTree/recoverBinarySearchTree.cpp), [Java](./algorithms/java/src/RecoverBinarySearchTree/RecoverBinarySearchTree.java)|Medium| |98|[Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)| [C++](./algorithms/cpp/validateBinarySearchTree/validateBinarySearchTree.cpp), [Java](./algorithms/java/src/validateBinarySearchTree/validateBinarySearchTree.java), [Python](./algorithms/python/ValidateBinarySearchTree/isValidBST.py)|Medium| |97|[Interleaving String](https://leetcode.com/problems/interleaving-string/)| [C++](./algorithms/cpp/interleavingString/interleavingString.cpp)|Hard| |96|[Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/)| [C++](./algorithms/cpp/uniqueBinarySearchTrees/uniqueBinarySearchTrees.cpp), [Python](./algorithms/python/UniqueBinarySearchTrees/numTrees.py)|Medium| From e06d446c8b9194b00ab8c4de1b5984875796b5b7 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sat, 23 Apr 2022 21:51:21 +0200 Subject: [PATCH 17/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b36d331e..bf01cea1 100644 --- a/README.md +++ b/README.md @@ -543,7 +543,7 @@ LeetCode |23|[Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)| [C++](./algorithms/cpp/mergeKSortedLists/mergeKSortedLists.cpp)|Hard| |22|[Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [C++](./algorithms/cpp/generateParentheses/generateParentheses.cpp)|Medium| |21|[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./algorithms/cpp/mergeTwoSortedList/mergeTwoSortedList.cpp)|Easy| -|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./algorithms/cpp/validParentheses/validParentheses.cpp)|Easy| +|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./algorithms/cpp/validParentheses/validParentheses.cpp), [Java](./algorithms/java/src/ValidParentheses/ValidParentheses.java)|Easy| |19|[Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [C++](./algorithms/cpp/removeNthNodeFromEndOfList/removeNthNodeFromEndOfList.cpp), [Python](./algorithms/python/RemoveNthNodeFromEndOfList/removeNthFromEnd.py)|Easy| |18|[4Sum](https://leetcode.com/problems/4sum/)| [C++](./algorithms/cpp/4Sum/4Sum.cpp)|Medium| |17|[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [C++](./algorithms/cpp/letterCombinationsOfAPhoneNumber/letterCombinationsOfAPhoneNumber.cpp)|Medium| From 87c9f11177fae0d4273143eb64ab80c05ede47b4 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 01:30:17 +0200 Subject: [PATCH 18/42] Update LengthOfLastWord.java --- .../java/src/lengthOfLastWord/LengthOfLastWord.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java b/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java index 2e661629..72e29b9d 100644 --- a/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java +++ b/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java @@ -42,3 +42,12 @@ public int lengthOfLastWord(String s) { } } + +// ANOTHER POSIBLE SOLUTION: + +class Solution { + public int lengthOfLastWord(String s) { + String[] a = s.split(" "); + return a[a.length-1].length(); + } +} From fa892268ee6c2e630f4fdc012debeee7f8c7adee Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 01:41:58 +0200 Subject: [PATCH 19/42] Create ExcelSheetColumnNumber.java --- .../ExcelSheetColumnNumber.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java diff --git a/algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java b/algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java new file mode 100644 index 00000000..79409fa1 --- /dev/null +++ b/algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java @@ -0,0 +1,61 @@ +// Source : https://leetcode.com/problems/excel-sheet-column-number/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * Given a string columnTitle that represents the column title as appear in an + * Excel sheet, return its corresponding column number. + * + * For example: + * A -> 1 + * B -> 2 + * C -> 3 + * ... + * Z -> 26 + * AA -> 27 + * AB -> 28 + * ... + * + * Example 1: + * + * Input: columnTitle = "A" + * Output: 1 + * + * Example 2: + * + * Input: columnTitle = "AB" + * Output: 28 + * Explanation: + * + * Example 3: + * + * Input: columnTitle = "ZY" + * Output: 701 + * + * 1 <= columnTitle.length <= 7 + * columnTitle consists only of uppercase English letters. + * columnTitle is in the range ["A", "FXSHRXW"]. + * + * Explanation of the solution: + * + * 1. While we have given less candies than the ones we had at the beginning (while(total < candies){...}) + * + * 2. Use count % num_people == 0 to determine the current index of the people. + ******************************************************************************************************/ + +class Solution { + public int titleToNumber(String columnTitle) { + int res = 0, cnt = 0; + String letras = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + int exponente = columnTitle.length()-1; + if(exponente == 0){ + return letras.indexOf(columnTitle)+1; + } + while(exponente != -1){ + res += (int) ((letras.indexOf(String.valueOf(columnTitle.charAt(cnt)))+1)*Math.pow(26, exponente)); + exponente--; + cnt++; + } + return res; + } +} From 5f8eadffa4c6054ba26040c278b60227ce779e32 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 01:42:44 +0200 Subject: [PATCH 20/42] Update ExcelSheetColumnNumber.java --- .../ExcelSheetColumnNumber/ExcelSheetColumnNumber.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java b/algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java index 79409fa1..f3b73c6d 100644 --- a/algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java +++ b/algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java @@ -34,13 +34,7 @@ * * 1 <= columnTitle.length <= 7 * columnTitle consists only of uppercase English letters. - * columnTitle is in the range ["A", "FXSHRXW"]. - * - * Explanation of the solution: - * - * 1. While we have given less candies than the ones we had at the beginning (while(total < candies){...}) - * - * 2. Use count % num_people == 0 to determine the current index of the people. + * columnTitle is in the range ["A", "FXSHRXW"] ******************************************************************************************************/ class Solution { From 2708d72720f3bdd71117d27e7ea2fe854a255d56 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 01:43:48 +0200 Subject: [PATCH 21/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bf01cea1..696d2fc8 100644 --- a/README.md +++ b/README.md @@ -392,7 +392,7 @@ LeetCode |174|[Dungeon Game](https://leetcode.com/problems/dungeon-game/) | [C++](./algorithms/cpp/dungeonGame/dungeonGame.cpp)|Hard| |173|[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [C++](./algorithms/cpp/binarySearchTreeIterator/binarySearchTreeIterator.cpp), [Java](./algorithms/java/src/binarySearchTreeIterator/binarySearchTreeIterator.java), [Python](./algorithms/python/BinarySearchTreeIterator/BSTIterator.py)|Medium| |172|[Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [C++](./algorithms/cpp/factorialTrailingZeroes/factorialTrailingZeroes.cpp)|Easy| -|171|[Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [C++](./algorithms/cpp/excelSheetColumnNumber/excelSheetColumnNumber.cpp)|Easy| +|171|[Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [C++](./algorithms/cpp/excelSheetColumnNumber/excelSheetColumnNumber.cpp), [Java](./algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java)|Easy| |170|[Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) 🔒 | [C++](./algorithms/cpp/twoSum/twoSum.III.cpp)|Easy| |169|[Majority Element](https://leetcode.com/problems/majority-element/) | [C++](./algorithms/cpp/majorityElement/majorityElement.cpp)|Easy| |168|[Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [C++](./algorithms/cpp/excelSheetColumnTitle/excelSheetColumnTitle.cpp)|Easy| From cdb8b7d67c60d9525023b92baf62c4075a554896 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 01:57:31 +0200 Subject: [PATCH 22/42] Create HappyNumber.java --- .../java/src/HappyNumber/HappyNumber.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 algorithms/java/src/HappyNumber/HappyNumber.java diff --git a/algorithms/java/src/HappyNumber/HappyNumber.java b/algorithms/java/src/HappyNumber/HappyNumber.java new file mode 100644 index 00000000..24efb85c --- /dev/null +++ b/algorithms/java/src/HappyNumber/HappyNumber.java @@ -0,0 +1,55 @@ +// Source : https://leetcode.com/problems/happy-number/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Write an algorithm to determine if a number n is happy. + * A happy number is a number defined by the following process: + * + * Starting with any positive integer, replace the number by the sum of the squares of its digits. + * + * Repeat the process until the number equals 1 (where it will stay), + * or it loops endlessly in a cycle which does not include 1. + * + * Those numbers for which this process ends in 1 are happy. + * + * Return true if n is a happy number, and false if not. + * + * Example 1: + * + * Input: n = 19 + * Output: true + * Explanation: +1^2 + 9^2 = 82 +8^2 + 2^2 = 68 +6^2 + 8^2 = 100 +1^2 + 0^2 + 0^2 = 1 + * + * Example 2: + * + * Input: n = 2 + * Output: false + * + * Constraints: + * + * 1 <= n <= 2^31 - 1 + ******************************************************************************************************/ + +class Solution { + public boolean isHappy(int n) { + while(n != 1){ + if(n == 7) + return true; + else if(n <= 9) + return false; + int num = 0; + while(n > 0){ + num += Math.pow(n % 10, 2); + n /= 10; + } + n=num; + } + return true; + } +} From 1b2753205e2f543301deb91174b50ad810f1b60f Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 01:58:44 +0200 Subject: [PATCH 23/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 696d2fc8..09378d89 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,7 @@ LeetCode |205|[Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/)| [C++](./algorithms/cpp/isomorphicStrings/IsomorphicStrings.cpp)|Easy| |204|[Count Primes](https://leetcode.com/problems/count-primes/)| [C++](./algorithms/cpp/countPrimes/CountPrimes.cpp)|Easy| |203|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [C++](./algorithms/cpp/removeLinkedListElements/RemoveLinkedListElements.cpp)|Easy| -|202|[Happy Number](https://leetcode.com/problems/happy-number/)| [C++](./algorithms/cpp/happyNumber/HappyNumber.cpp), [Python](./algorithms/python/HappyNumber/isHappy.py)|Easy| +|202|[Happy Number](https://leetcode.com/problems/happy-number/)| [C++](./algorithms/cpp/happyNumber/HappyNumber.cpp), [Python](./algorithms/python/HappyNumber/isHappy.py), [Java](./algorithms/java/src/HappyNumber/HappyNumber.java)|Easy| |201|[Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/)| [C++](./algorithms/cpp/bitwiseANDOfNumbersRange/BitwiseAndOfNumbersRange.cpp)|Medium| |200|[Number of Islands](https://leetcode.com/problems/number-of-islands/)| [C++](./algorithms/cpp/numberOfIslands/NumberOfIslands.cpp), [Python](./algorithms/python/NumberOfIslands/numIslands.py)|Medium| |199|[Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/)| [C++](./algorithms/cpp/binaryTreeRightSideView/binaryTreeRightSideView.cpp)|Medium| From 07f37f892f18ee34fdc5eca1ca35ce1b3bf9d089 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 10:09:49 +0200 Subject: [PATCH 24/42] Update MyQueue.java --- algorithms/java/src/myQueue/MyQueue.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/algorithms/java/src/myQueue/MyQueue.java b/algorithms/java/src/myQueue/MyQueue.java index 51e545db..c95cf305 100644 --- a/algorithms/java/src/myQueue/MyQueue.java +++ b/algorithms/java/src/myQueue/MyQueue.java @@ -99,3 +99,16 @@ public boolean empty() { return size == 0 ? true : false; } } + +//ANOTHER POSIBLE SOLUTION BY: DIEGO RUIZ PIQUERAS (PIKERAS72) + +class Solution { + public boolean isPowerOfTwo(int n) { + double num =Math.log10(n)/ Math.log10(2); + + if(num % 1 != 0){ + return false; + } + return true; + } +} From afc502dc43d1abef5f4ae75b3b57a3d909c64347 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 10:10:31 +0200 Subject: [PATCH 25/42] Update MyQueue.java --- algorithms/java/src/myQueue/MyQueue.java | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/algorithms/java/src/myQueue/MyQueue.java b/algorithms/java/src/myQueue/MyQueue.java index c95cf305..51e545db 100644 --- a/algorithms/java/src/myQueue/MyQueue.java +++ b/algorithms/java/src/myQueue/MyQueue.java @@ -99,16 +99,3 @@ public boolean empty() { return size == 0 ? true : false; } } - -//ANOTHER POSIBLE SOLUTION BY: DIEGO RUIZ PIQUERAS (PIKERAS72) - -class Solution { - public boolean isPowerOfTwo(int n) { - double num =Math.log10(n)/ Math.log10(2); - - if(num % 1 != 0){ - return false; - } - return true; - } -} From c5e9a5238d8e4f534f17fd43928cdae38c11f313 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 10:16:16 +0200 Subject: [PATCH 26/42] Create PowerOfTwo.java --- .../java/src/PowerOfTwo/PowerOfTwo.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 algorithms/java/src/PowerOfTwo/PowerOfTwo.java diff --git a/algorithms/java/src/PowerOfTwo/PowerOfTwo.java b/algorithms/java/src/PowerOfTwo/PowerOfTwo.java new file mode 100644 index 00000000..b121c503 --- /dev/null +++ b/algorithms/java/src/PowerOfTwo/PowerOfTwo.java @@ -0,0 +1,45 @@ +// Source : https://leetcode.com/problems/power-of-two/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given an integer n, return true if it is a power of two. Otherwise, return false. + * + * An integer n is a power of two, if there exists an integer x such that n == 2x. + * + * Example 1: + * + * Input: n = 1 + * Output: true + * Explanation: 2^0 = 1 + * + * Example 2: + * + * Input: n = 16 + * Output: true + * Explanation: 2^4 = 16 + * + * Example 3: + * + * Input: n = 3 + * Output: false + * + * Constraints: + * + * 1 <= n <= 2^31 - 1 + * + * Explanation of the solution: + * + * After doing the log2(n), if the result have no decimal part, it means that 'n' is a power of two. + ******************************************************************************************************/ + +class Solution { + public boolean isPowerOfTwo(int n) { + double num =Math.log10(n)/ Math.log10(2); + if(num % 1 != 0){ + return false; + } + return true; + } +} From fb445ab01a3dc6c48ca6acf54b96accebb2f93b7 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 10:17:06 +0200 Subject: [PATCH 27/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 09378d89..9d7498ab 100644 --- a/README.md +++ b/README.md @@ -348,7 +348,7 @@ LeetCode |234|[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./algorithms/cpp/palindromeLinkedList/PalindromeLinkedList.cpp)|Easy| |233|[Number of Digit One](https://leetcode.com/problems/number-of-digit-one/)| [C++](./algorithms/cpp/numberOfDigitOne/NumberOfDigitOne.cpp)|Medium| |232|[Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)| [C++](./algorithms/cpp/implementQueueUsingStacks/ImplementQueueUsingStacks.cpp), [Java](./algorithms/java/src/myQueue/MyQueue.java)|Easy| -|231|[Power of Two](https://leetcode.com/problems/power-of-two/)| [C++](./algorithms/cpp/powerOfTwo/PowerOfTwo.cpp)|Easy| +|231|[Power of Two](https://leetcode.com/problems/power-of-two/)| [C++](./algorithms/cpp/powerOfTwo/PowerOfTwo.cpp), [Java](./algorithms/java/src/PowerOfTwo/PowerOfTwo.java)|Easy| |230|[Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)| [C++](./algorithms/cpp/kthSmallestElementInaBST/KthSmallestElementInABst.cpp), [Python](./algorithms/python/KthSmallestElementInABST/kthSmallest.py)|Medium| |229|[Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./algorithms/cpp/majorityElement/majorityElement.II.cpp)|Medium| |228|[Summary Ranges](https://leetcode.com/problems/summary-ranges/)| [C++](./algorithms/cpp/summaryRanges/SummaryRanges.cpp)|Easy| From 0edbcf8d9d9f850d881a386de6ffe9e1b129c322 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 10:19:55 +0200 Subject: [PATCH 28/42] Create PowerOfThree.java --- .../java/src/PowerOfThree/PowerOfThree.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 algorithms/java/src/PowerOfThree/PowerOfThree.java diff --git a/algorithms/java/src/PowerOfThree/PowerOfThree.java b/algorithms/java/src/PowerOfThree/PowerOfThree.java new file mode 100644 index 00000000..c847e6a9 --- /dev/null +++ b/algorithms/java/src/PowerOfThree/PowerOfThree.java @@ -0,0 +1,43 @@ +// Source : https://leetcode.com/problems/power-of-three/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given an integer n, return true if it is a power of three. Otherwise, return false. + * + * An integer n is a power of three, if there exists an integer x such that n == 3x. + * + * Example 1: + * + * Input: n = 27 + * Output: true + * + * Example 2: + * + * Input: n = 0 + * Output: false + * + * Example 3: + * + * Input: n = 9 + * Output: true + * + * Constraints: + * + * -2^31 <= n <= 2^31 - 1 + * + * Explanation of the solution: + * + * After doing the log3(n), if the result have no decimal part, it means that 'n' is a power of three. + ******************************************************************************************************/ + +class Solution { + public boolean isPowerOfThree(int n) { + double num = Math.log10(n) / Math.log10(3); + if(num % 1 != 0){ + return false; + } + return true; + } +} From 18316f25a7d8a83449b5d8c46fe07632e35e28c6 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 10:22:08 +0200 Subject: [PATCH 29/42] Create PowerOfFour.java --- .../java/src/PowerOfFour/PowerOfFour.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 algorithms/java/src/PowerOfFour/PowerOfFour.java diff --git a/algorithms/java/src/PowerOfFour/PowerOfFour.java b/algorithms/java/src/PowerOfFour/PowerOfFour.java new file mode 100644 index 00000000..8411f7ae --- /dev/null +++ b/algorithms/java/src/PowerOfFour/PowerOfFour.java @@ -0,0 +1,43 @@ +// Source : https://leetcode.com/problems/power-of-four/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given an integer n, return true if it is a power of four. Otherwise, return false. + * + * An integer n is a power of four, if there exists an integer x such that n == 4x. + * + * Example 1: + * + * Input: n = 16 + * Output: true + * + * Example 2: + * + * Input: n = 5 + * Output: false + * + * Example 3: + * + * Input: n = 1 + * Output: true + * + * Constraints: + * + * -2^31 <= n <= 2^31 - 1 + * + * Explanation of the solution: + * + * After doing the log4(n), if the result have no decimal part, it means that 'n' is a power of four. + ******************************************************************************************************/ + +class Solution { + public boolean isPowerOfFour(int n) { + double num = Math.log10(n) / Math.log10(4); + if(num % 1 != 0) { + return false; + } + return true; + } +} From cb9f236e583043b387a426fbe4a244a37586ec3d Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 10:24:44 +0200 Subject: [PATCH 30/42] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9d7498ab..4339b43a 100644 --- a/README.md +++ b/README.md @@ -285,7 +285,7 @@ LeetCode |345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| |344|[Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./algorithms/cpp/reverseString/ReverseString.cpp)|Easy| |343|[Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./algorithms/cpp/integerBreak/IntegerBreak.cpp)|Medium| -|342|[Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./algorithms/cpp/powerOfFour/PowerOfFour.cpp)|Easy| +|342|[Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./algorithms/cpp/powerOfFour/PowerOfFour.cpp), [Java](./algorithms/java/src/PowerOfFour/PowerOfFour.java)|Easy| |341|[Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/) | [C++](./algorithms/cpp/flattenNestedListIterator/FlattenNestedListIterator.cpp)|Medium| |338|[Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./algorithms/cpp/countingBits/CountingBits.cpp)|Medium| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp), [Python](./algorithms/python/HouseRobberIII/rob.py)|Medium| @@ -297,7 +297,7 @@ LeetCode |329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp)|Medium| |328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | [C++](./algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp)|Easy| |327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard| -|326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy| +|326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp), [Java](./algorithms/java/src/PowerOfThree/PowerOfThree.java)|Easy| |324|[Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./algorithms/cpp/wiggleSort/WiggleSort.II.cpp)|Medium| |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |321|[Create Maximum Number](https://leetcode.com/problems/create-maximum-number/) | [C++](./algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp)|Hard| From 22ec019b6fc73250b3292a9932aefba8262c92d2 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 10:39:08 +0200 Subject: [PATCH 31/42] Create ThirdMaximumNumber.java --- .../ThirdMaximumNumber.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 algorithms/java/src/ThirdMaximumNumber/ThirdMaximumNumber.java diff --git a/algorithms/java/src/ThirdMaximumNumber/ThirdMaximumNumber.java b/algorithms/java/src/ThirdMaximumNumber/ThirdMaximumNumber.java new file mode 100644 index 00000000..32a731bc --- /dev/null +++ b/algorithms/java/src/ThirdMaximumNumber/ThirdMaximumNumber.java @@ -0,0 +1,72 @@ +// Source : https://leetcode.com/problems/third-maximum-number/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 22-04-2022 + +/***************************************************************************************************** + * + * Given an integer array nums, return the third distinct maximum number in + * this array. If the third maximum does not exist, return the maximum number. + * + * Example 1: + * + * Input: nums = [3,2,1] + * Output: 1 + * Explanation: + * The first distinct maximum is 3. + * The second distinct maximum is 2. + * The third distinct maximum is 1. + * + * Example 2: + * + * Input: nums = [1,2] + * Output: 2 + * Explanation: + * The first distinct maximum is 2. + * The second distinct maximum is 1. + * The third distinct maximum does not exist, so the maximum (2) is returned instead. + * + * Example 3: + * + * Input: nums = [2,2,3,1] + * Output: 1 + * Explanation: + * The first distinct maximum is 3. + * The second distinct maximum is 2 (both 2's are counted together since they have the same value). + * The third distinct maximum is 1. + * + * Constraints: + * + * 1 <= nums.length <= 10^4 + * -2^31 <= nums[i] <= 2^31 - 1 + * + * Explanation of the solution: + * + * 1. We establish the three variables to the (Integer.MIN_VALUE - 1) + * + * 2. We analyze the array 'nums' and we update the variables when a bigger number is found + ******************************************************************************************************/ + +class Solution { + public int thirdMax(int[] nums) { + long max1 = -2147483649L, max2 = -2147483649L, max3 = -2147483649L; + for(int i : nums){ + if(i>max1){ + if(i> max2){ + if(i > max3){ + max1 = max2; + max2 = max3; + max3 = i; + }else if(i!=max3 && i != max2){ + max1 = max2; + max2 = i; + } + }else if(i!=max1 && i!=max2){max1=i;} + } + } + if(max1==-2147483649L){ + return (int)max3; + }else{ + return (int)max1; + } + } +} From 58bed684547a68b1519bcd0b2c6e29d01457ad50 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:04:29 +0200 Subject: [PATCH 32/42] Create MinimumRemoveToMakeValidParentheses.java --- .../MinimumRemoveToMakeValidParentheses.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 algorithms/java/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java diff --git a/algorithms/java/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java b/algorithms/java/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java new file mode 100644 index 00000000..dd44deb1 --- /dev/null +++ b/algorithms/java/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java @@ -0,0 +1,69 @@ +// Source : https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given a string s of '(' , ')' and lowercase English characters. + * + * Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) + * so that the resulting parentheses string is valid and return any valid string. + * + * Formally, a parentheses string is valid if and only if: + * It is the empty string, contains only lowercase characters, or + * It can be written as AB (A concatenated with B), where A and B are valid strings, or + * It can be written as (A), where A is a valid string. + * + * Example 1: + * + * Input: s = "lee(t(c)o)de)" + * Output: "lee(t(c)o)de" + * Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. + * + * Example 2: + * + * Input: s = "a)b(c)d" + * Output: "ab(c)d" + * + * Example 3: + * + * Input: s = "))((" + * Output: "" + * Explanation: An empty string is also valid. + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s[i] is either'(' , ')', or lowercase English letter. + * + * Explanation of the solution: + * + * 1. Analyze the string to know how many valid parentheses are in 's'. + * +* 2. Analyze again the string and return the string deleting the invalid parentheses. +* +* 3. Return the reversed string. + ******************************************************************************************************/ + +class Solution { + public String minRemoveToMakeValid(String s) { + StringBuilder comprobar = new StringBuilder(); + int open = 0; + for(char c : s.toCharArray()) { + if(c =='(') { + open++; + } + else if(c == ')') { + if(open == 0) continue; + open--; + } + comprobar.append(c); + } + StringBuilder result = new StringBuilder(); + for(int i=comprobar.length()-1 ; i>=0 ; i-- ){ + if(comprobar.charAt(i) == '(' && open-- > 0) continue; + result.append(comprobar.charAt(i)); + } + return result.reverse().toString(); + } +} From e61a4f664d38345dac3f567eb3056c2643bebb5a Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:07:41 +0200 Subject: [PATCH 33/42] Delete algorithms/java/MinimumRemoveToMakeValidParentheses directory --- .../MinimumRemoveToMakeValidParentheses.java | 69 ------------------- 1 file changed, 69 deletions(-) delete mode 100644 algorithms/java/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java diff --git a/algorithms/java/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java b/algorithms/java/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java deleted file mode 100644 index dd44deb1..00000000 --- a/algorithms/java/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java +++ /dev/null @@ -1,69 +0,0 @@ -// Source : https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ -// Author : Diego Ruiz Piqueras (Pikeras72) -// Date : 24-04-2022 - -/***************************************************************************************************** - * - * Given a string s of '(' , ')' and lowercase English characters. - * - * Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) - * so that the resulting parentheses string is valid and return any valid string. - * - * Formally, a parentheses string is valid if and only if: - * It is the empty string, contains only lowercase characters, or - * It can be written as AB (A concatenated with B), where A and B are valid strings, or - * It can be written as (A), where A is a valid string. - * - * Example 1: - * - * Input: s = "lee(t(c)o)de)" - * Output: "lee(t(c)o)de" - * Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. - * - * Example 2: - * - * Input: s = "a)b(c)d" - * Output: "ab(c)d" - * - * Example 3: - * - * Input: s = "))((" - * Output: "" - * Explanation: An empty string is also valid. - * - * Constraints: - * - * 1 <= s.length <= 10^5 - * s[i] is either'(' , ')', or lowercase English letter. - * - * Explanation of the solution: - * - * 1. Analyze the string to know how many valid parentheses are in 's'. - * -* 2. Analyze again the string and return the string deleting the invalid parentheses. -* -* 3. Return the reversed string. - ******************************************************************************************************/ - -class Solution { - public String minRemoveToMakeValid(String s) { - StringBuilder comprobar = new StringBuilder(); - int open = 0; - for(char c : s.toCharArray()) { - if(c =='(') { - open++; - } - else if(c == ')') { - if(open == 0) continue; - open--; - } - comprobar.append(c); - } - StringBuilder result = new StringBuilder(); - for(int i=comprobar.length()-1 ; i>=0 ; i-- ){ - if(comprobar.charAt(i) == '(' && open-- > 0) continue; - result.append(comprobar.charAt(i)); - } - return result.reverse().toString(); - } -} From e34395982d9b730da558ae81333d6cb116923d71 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:08:36 +0200 Subject: [PATCH 34/42] Create MinimumRemoveToMakeValidParentheses.java --- .../MinimumRemoveToMakeValidParentheses.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 algorithms/java/src/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java diff --git a/algorithms/java/src/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java b/algorithms/java/src/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java new file mode 100644 index 00000000..dd44deb1 --- /dev/null +++ b/algorithms/java/src/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java @@ -0,0 +1,69 @@ +// Source : https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given a string s of '(' , ')' and lowercase English characters. + * + * Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) + * so that the resulting parentheses string is valid and return any valid string. + * + * Formally, a parentheses string is valid if and only if: + * It is the empty string, contains only lowercase characters, or + * It can be written as AB (A concatenated with B), where A and B are valid strings, or + * It can be written as (A), where A is a valid string. + * + * Example 1: + * + * Input: s = "lee(t(c)o)de)" + * Output: "lee(t(c)o)de" + * Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. + * + * Example 2: + * + * Input: s = "a)b(c)d" + * Output: "ab(c)d" + * + * Example 3: + * + * Input: s = "))((" + * Output: "" + * Explanation: An empty string is also valid. + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s[i] is either'(' , ')', or lowercase English letter. + * + * Explanation of the solution: + * + * 1. Analyze the string to know how many valid parentheses are in 's'. + * +* 2. Analyze again the string and return the string deleting the invalid parentheses. +* +* 3. Return the reversed string. + ******************************************************************************************************/ + +class Solution { + public String minRemoveToMakeValid(String s) { + StringBuilder comprobar = new StringBuilder(); + int open = 0; + for(char c : s.toCharArray()) { + if(c =='(') { + open++; + } + else if(c == ')') { + if(open == 0) continue; + open--; + } + comprobar.append(c); + } + StringBuilder result = new StringBuilder(); + for(int i=comprobar.length()-1 ; i>=0 ; i-- ){ + if(comprobar.charAt(i) == '(' && open-- > 0) continue; + result.append(comprobar.charAt(i)); + } + return result.reverse().toString(); + } +} From 17c5e421248a0eedabe788e0f564b6042d7c9e3a Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:10:25 +0200 Subject: [PATCH 35/42] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4339b43a..a7974485 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ LeetCode |1375|[Bulb Switcher III](https://leetcode.com/problems/bulb-switcher-iii) | [C++](./algorithms/cpp/bulbSwitcher/BulbSwitcher.III.cpp)|Medium| |1353|[Maximum Number of Events That Can Be Attended](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/) | [C++](./algorithms/cpp/maximumNumberOfEventsThatCanBeAttended/MaximumNumberOfEventsThatCanBeAttended.cpp)|Medium| |1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/) | [C++](./algorithms/cpp/filterRestaurantsByVeganFriendlyPriceAndDistance/FilterRestaurantsByVeganFriendlyPriceAndDistance.cpp)|Medium| +|1249|[Minimum Remove to Make Valid Parentheses](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/) | [Java](./algorithms/java/src/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java)|Medium| |1207|[Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C++](./algorithms/cpp/uniqueNumberOfOccurrences/Unique-Number-of-Occurrences.cpp)|Easy| |1170|[Compare Strings by Frequency of the Smallest Character](https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/) | [C++](./algorithms/cpp/compareStringsByFrequencyOfTheSmallestCharacter/CompareStringsByFrequencyOfTheSmallestCharacter.cpp)|Easy| |1103|[Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people/) | [Java](./algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java)|Easy| @@ -242,7 +243,7 @@ LeetCode |418|[SentenceScreenFitting](https://leetcode.com/problems/sentence-screen-fitting/) 🔒 | [C++](./algorithms/cpp/sentenceScreenFitting/sentenceScreenFitting.cpp)|Easy| |416|[Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/description/) | [C++](./algorithms/cpp/partitionEqualSubsetSum/PartitionEqualSubsetSum.cpp)|Medium| |415|[Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./algorithms/cpp/addStrings/AddStrings.cpp)|Easy| -|414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp), [Python](./algorithms/python/ThirdMaximumNumber/thirdMax.py)|Easy| +|414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp), [Python](./algorithms/python/ThirdMaximumNumber/thirdMax.py), [Java](./algorithms/java/src/ThirdMaximumNumber/ThirdMaximumNumber.java)|Easy| |413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp)|Medium| |412|[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./algorithms/cpp/fizzBuzz/FizzBuzz.cpp)|Easy| |410|[Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) | [C++](./algorithms/cpp/splitArrayLargestSum/SplitArrayLargestSum.cpp)|Hard| From 376480dc4b01751d4e640b25b97277bda5ea67f1 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:21:44 +0200 Subject: [PATCH 36/42] Create SubtractTheProductAndSumOfDigitsOfAnInteger.java --- ...ctTheProductAndSumOfDigitsOfAnInteger.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 algorithms/java/src/SubtractTheProductAndSumOfDigitsOfAnInteger/SubtractTheProductAndSumOfDigitsOfAnInteger.java diff --git a/algorithms/java/src/SubtractTheProductAndSumOfDigitsOfAnInteger/SubtractTheProductAndSumOfDigitsOfAnInteger.java b/algorithms/java/src/SubtractTheProductAndSumOfDigitsOfAnInteger/SubtractTheProductAndSumOfDigitsOfAnInteger.java new file mode 100644 index 00000000..6258a67f --- /dev/null +++ b/algorithms/java/src/SubtractTheProductAndSumOfDigitsOfAnInteger/SubtractTheProductAndSumOfDigitsOfAnInteger.java @@ -0,0 +1,50 @@ +// Source : https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given an integer number n, return the difference between the product + * of its digits and the sum of its digits. + * + * Example 1: + * + * Input: n = 234 + * Output: 15 + * Explanation: + * Product of digits = 2 * 3 * 4 = 24 + * Sum of digits = 2 + 3 + 4 = 9 + * Result = 24 - 9 = 15 + * + * Example 2: + * + * Input: n = 4421 + * Output: 21 + * Explanation: + * Product of digits = 4 * 4 * 2 * 1 = 32 + * Sum of digits = 4 + 4 + 2 + 1 = 11 + * Result = 32 - 11 = 21 + * + * Constraints: + * + * 1 <= n <= 10^5 + * + * Explanation of the solution: + * + * 1. We analyze the String 'ns' char by char and we add and multiply both vatiables (product and sum) each time. + * + * 2. We return the subtraction of it. + ******************************************************************************************************/ + +class Solution { + public int subtractProductAndSum(int n) { + int prod = 1, sum = 0,act; + String ns = String.valueOf(n); + for(int i = 0; i < ns.length(); i++){ + act = Integer.parseInt(String.valueOf(ns.charAt(i))); + prod *= act; + sum += act; + } + return prod-sum; + } +} From 8c306eb6bf1b658a44895351f1ac6c02d179b9a6 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:23:12 +0200 Subject: [PATCH 37/42] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a7974485..512fa2de 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ LeetCode |1375|[Bulb Switcher III](https://leetcode.com/problems/bulb-switcher-iii) | [C++](./algorithms/cpp/bulbSwitcher/BulbSwitcher.III.cpp)|Medium| |1353|[Maximum Number of Events That Can Be Attended](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/) | [C++](./algorithms/cpp/maximumNumberOfEventsThatCanBeAttended/MaximumNumberOfEventsThatCanBeAttended.cpp)|Medium| |1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/) | [C++](./algorithms/cpp/filterRestaurantsByVeganFriendlyPriceAndDistance/FilterRestaurantsByVeganFriendlyPriceAndDistance.cpp)|Medium| +|1281|[Subtract the Product and Sum of Digits of an Integer](https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/) | [Java](./algorithms/java/src/SubtractTheProductAndSumOfDigitsOfAnInteger/SubtractTheProductAndSumOfDigitsOfAnInteger.java)|Easy| |1249|[Minimum Remove to Make Valid Parentheses](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/) | [Java](./algorithms/java/src/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java)|Medium| |1207|[Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C++](./algorithms/cpp/uniqueNumberOfOccurrences/Unique-Number-of-Occurrences.cpp)|Easy| |1170|[Compare Strings by Frequency of the Smallest Character](https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/) | [C++](./algorithms/cpp/compareStringsByFrequencyOfTheSmallestCharacter/CompareStringsByFrequencyOfTheSmallestCharacter.cpp)|Easy| From 6a748c6d3b826c68851dd3839851e3ab43e4515b Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:31:32 +0200 Subject: [PATCH 38/42] Create CanMakeArithmeticProgressionFromSequence.java --- ...MakeArithmeticProgressionFromSequence.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 algorithms/java/src/CanMakeArithmeticProgressionFromSequence/CanMakeArithmeticProgressionFromSequence.java diff --git a/algorithms/java/src/CanMakeArithmeticProgressionFromSequence/CanMakeArithmeticProgressionFromSequence.java b/algorithms/java/src/CanMakeArithmeticProgressionFromSequence/CanMakeArithmeticProgressionFromSequence.java new file mode 100644 index 00000000..9792715d --- /dev/null +++ b/algorithms/java/src/CanMakeArithmeticProgressionFromSequence/CanMakeArithmeticProgressionFromSequence.java @@ -0,0 +1,57 @@ +// Source : https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * A sequence of numbers is called an arithmetic progression if the + * difference between any two consecutive elements is the same. + * + * Given an array of numbers arr, return true if the array can be + * rearranged to form an arithmetic progression. Otherwise, return false. + * + * Example 1: + * + * Input: arr = [3,5,1] + * Output: true + * Explanation: We can reorder the elements as [1,3,5] or [5,3,1] + * with differences 2 and -2 respectively, between each consecutive elements. + * + * Example 2: + * + * Input: arr = [1,2,4] + * Output: false + * Explanation: There is no way to reorder the elements to obtain an arithmetic progression. + * + * Constraints: + * + * 2 <= arr.length <= 1000 + * -10^6 <= arr[i] <= 10^6 + * + * Explanation of the solution: + * + * 1. We sort the array 'arr' to check the distance between the first two numbers. + * + * 2. We analyze the array looking if all the numbers have the exact same distance + * between them compared to the two first numbers. + ******************************************************************************************************/ + +class Solution { + public boolean canMakeArithmeticProgression(int[] arr) { + int dis, disBase = 0; + boolean yes = true; + Arrays.sort(arr); + for(int i = 0; i < arr.length-1; i++){ + if(i == 0){ + disBase = arr[i+1]-arr[i]; + }else{ + dis = arr[i+1]-arr[i]; + if(dis != disBase){ + yes = false; + break; + } + } + } + return yes; + } +} From 9e2be500198943dd87dd629a79c1f5f8132a6f61 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:32:37 +0200 Subject: [PATCH 39/42] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 512fa2de..c972328d 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ LeetCode |1524|[Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/) | [C++](./algorithms/cpp/numberOfSubArraysWithOddSum/NumberOfSubArraysWithOddSum.cpp)|Medium| |1523|[Count Odd Numbers in an Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/) | [C++](./algorithms/cpp/countOddNumbersInAnIntervalRange/CountOddNumbersInAnIntervalRange.cpp)|Easy| |1513|[Number of Substrings With Only 1s](https://leetcode.com/problems/number-of-substrings-with-only-1s/) | [C++](./algorithms/cpp/numberOfSubstringsWithOnly1s/NumberOfSubstringsWithOnly1s.cpp)|Medium| +|1502|[Can Make Arithmetic Progression From Sequence](https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/) | [Java](./algorithms/java/src/CanMakeArithmeticProgressionFromSequence/CanMakeArithmeticProgressionFromSequence.java)|Easy| |1470|[Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/) | [C++](./algorithms/cpp/shuffleTheArray/ShuffleTheArray.cpp)|Easy| |1464|[Maximum Product of Two Elements in an Array](https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/) | [C++](./algorithms/cpp/maximumProductOfTwoElementsInAnArray/MaximumProductOfTwoElementsInAnArray.cpp)|Easy| |1460|[Make Two Arrays Equal by Reversing Sub-arrays](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/) | [C++](./algorithms/cpp/twoArraysEqualByReversingSubArrays/MakeTwoArraysEqualByReversingSubArrays.cpp)|Easy| From 72db0633af6e0bd5b4d8a7c801cd64c474ad1c73 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:48:46 +0200 Subject: [PATCH 40/42] Create SignOfTheProductOfAnArray.java --- .../SignOfTheProductOfAnArray.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 algorithms/java/src/SignOfTheProductOfAnArray/SignOfTheProductOfAnArray.java diff --git a/algorithms/java/src/SignOfTheProductOfAnArray/SignOfTheProductOfAnArray.java b/algorithms/java/src/SignOfTheProductOfAnArray/SignOfTheProductOfAnArray.java new file mode 100644 index 00000000..79f35e48 --- /dev/null +++ b/algorithms/java/src/SignOfTheProductOfAnArray/SignOfTheProductOfAnArray.java @@ -0,0 +1,60 @@ +// Source : https://leetcode.com/problems/sign-of-the-product-of-an-array/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * There is a function signFunc(x) that returns: + * 1 if x is positive. + * -1 if x is negative. + * 0 if x is equal to 0. + * + * You are given an integer array nums. Let product be the product of all values in the array nums. + * + * Return signFunc(product). + * + * Example 1: + * + * Input: nums = [-1,-2,-3,-4,3,2,1] + * Output: 1 + * Explanation: The product of all values in the array is 144, and signFunc(144) = 1 + * + * Example 2: + * + * Input: nums = [1,5,0,2,-3] + * Output: 0 + * Explanation: The product of all values in the array is 0, and signFunc(0) = 0 + * + * Example 3: + * + * Input: nums = [-1,1,-1,1,-1] + * Output: -1 + * Explanation: The product of all values in the array is -1, and signFunc(-1) = -1 + * + * Constraints: + * + * 1 <= nums.length <= 1000 + * -100 <= nums[i] <= 100 + * + * Explanation of the solution: + * + * 1. We analyze all the numbers in 'nums', if we encounter a 0, we return 0. + * + * 2. If we find a negative number we add 1 to de counter 'cnt', once we have finished analyzing, + * we return -1 if there is an odd number of '-' symbols. Otherwise we return 1. + ******************************************************************************************************/ + +class Solution { + public int arraySign(int[] nums) { + String num = ""; + int cnt = 0; + for(int i : nums){ + if(i == 0){ + return 0; + }else if(i < 0){ + cnt++; + } + } + if(cnt % 2 == 0){return 1;}else{return -1;} + } +} From 16a6c40058bc3987cc4da736d3b268471c32e79b Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:49:34 +0200 Subject: [PATCH 41/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c972328d..202ae6ff 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ LeetCode |1825|[Finding MK Average](https://leetcode.com/problems/finding-mk-average/) | [C++](./algorithms/cpp/findingMkAverage/FindingMkAverage.cpp)|Hard| |1824|[Minimum Sideway Jumps](https://leetcode.com/problems/minimum-sideway-jumps/) | [C++](./algorithms/cpp/minimumSidewayJumps/MinimumSidewayJumps.cpp)|Medium| |1823|[Find the Winner of the Circular Game](https://leetcode.com/problems/find-the-winner-of-the-circular-game/) | [C++](./algorithms/cpp/findTheWinnerOfTheCircularGame/FindTheWinnerOfTheCircularGame.cpp)|Medium| -|1822|[Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) | [C++](./algorithms/cpp/signOfTheProductOfAnArray/SignOfTheProductOfAnArray.cpp)|Easy| +|1822|[Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) | [C++](./algorithms/cpp/signOfTheProductOfAnArray/SignOfTheProductOfAnArray.cpp), [Java](./algorithms/java/src/SignOfTheProductOfAnArray/SignOfTheProductOfAnArray.java)|Easy| |1819|[Number of Different Subsequences GCDs](https://leetcode.com/problems/number-of-different-subsequences-gcds/) | [C++](./algorithms/cpp/numberOfDifferentSubsequencesGcds/NumberOfDifferentSubsequencesGcds.cpp)|Hard| |1818|[Minimum Absolute Sum Difference](https://leetcode.com/problems/minimum-absolute-sum-difference/) | [C++](./algorithms/cpp/minimumAbsoluteSumDifference/MinimumAbsoluteSumDifference.cpp)|Medium| |1817|[Finding the Users Active Minutes](https://leetcode.com/problems/finding-the-users-active-minutes/) | [C++](./algorithms/cpp/findingTheUsersActiveMinutes/FindingTheUsersActiveMinutes.cpp)|Medium| From 43bf2f64f9326f771b964b3206b5ee45fe80f207 Mon Sep 17 00:00:00 2001 From: Diego Ruiz Piqueras Date: Sun, 24 Apr 2022 11:56:20 +0200 Subject: [PATCH 42/42] Update LengthOfLastWord.java --- algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java b/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java index 72e29b9d..793260d0 100644 --- a/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java +++ b/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java @@ -43,7 +43,7 @@ public int lengthOfLastWord(String s) { } -// ANOTHER POSIBLE SOLUTION: +// ANOTHER POSIBLE SOLUTION BY: DIEGO RUIZ PIQUERAS (PIKERAS72) class Solution { public int lengthOfLastWord(String s) {