From 8bd9987b648aaf80b789480afce7c03a32ebb898 Mon Sep 17 00:00:00 2001 From: Shen Jie Date: Sun, 19 Nov 2017 15:30:44 +0800 Subject: [PATCH 1/7] Add java solution for 13 --- java/_013RomanToInteger.java | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 java/_013RomanToInteger.java diff --git a/java/_013RomanToInteger.java b/java/_013RomanToInteger.java new file mode 100644 index 0000000..40fe606 --- /dev/null +++ b/java/_013RomanToInteger.java @@ -0,0 +1,36 @@ +import java.util.HashMap; +import java.util.Map; + +/** + * Created by drfish on 25/06/2017. + */ +public class _013RomanToInteger { + public int romanToInt(String s) { + Map map = new HashMap() {{ + put('M', 1000); + put('D', 500); + put('C', 100); + put('L', 50); + put('X', 10); + put('V', 5); + put('I', 1); + }}; + int result = 0; + for (int i = 0; i < s.length(); i++) { + if (i > 0 && map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) { + result -= map.get(s.charAt(i - 1)); + result += map.get(s.charAt(i)) - map.get(s.charAt(i - 1)); + } else { + result += map.get(s.charAt(i)); + } + } + return result; + } + + public static void main(String[] args) { + _013RomanToInteger solution = new _013RomanToInteger(); + assert 12 == solution.romanToInt("XII"); + assert 21 == solution.romanToInt("XXI"); + assert 99 == solution.romanToInt("XCIX"); + } +} From aef77bcb103461680786e0634dc15ffb25d0db0d Mon Sep 17 00:00:00 2001 From: "lihen.sj" Date: Wed, 29 Nov 2017 13:34:35 +0800 Subject: [PATCH 2/7] Java solution 283 & 292 --- java/_283MoveZeroes.java | 26 ++++++++++++++++++++++++++ java/_292NimGame.java | 12 ++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 java/_283MoveZeroes.java create mode 100644 java/_292NimGame.java diff --git a/java/_283MoveZeroes.java b/java/_283MoveZeroes.java new file mode 100644 index 0000000..0c93be9 --- /dev/null +++ b/java/_283MoveZeroes.java @@ -0,0 +1,26 @@ +/** + * Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. + * + * For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. + * + * Note: + * You must do this in-place without making a copy of the array. + * Minimize the total number of operations. + */ + +public class _283MoveZeroes { + public void moveZeroes(int[] nums) { + if (nums == null || nums.length == 0) { + return; + } + int index = 0; + for (int i = 0; i < nums.length; i++) { + if (nums[i] != 0) { + nums[index++] = nums[i]; + } + } + for (int i = index; i < nums.length; i++) { + nums[i] = 0; + } + } +} \ No newline at end of file diff --git a/java/_292NimGame.java b/java/_292NimGame.java new file mode 100644 index 0000000..b1727fb --- /dev/null +++ b/java/_292NimGame.java @@ -0,0 +1,12 @@ +/** + * You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. + * + * Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. + * + * For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. + */ +public class _292NimGame { + public boolean canWinNim(int n) { + return n % 4 != 0; + } +} \ No newline at end of file From 817ea162a34efb5c0a18249836a4f34534475e58 Mon Sep 17 00:00:00 2001 From: drfish <1993sj1993@gmail.com> Date: Wed, 29 Nov 2017 20:07:48 +0800 Subject: [PATCH 3/7] Java solution 257 & 258 --- java/_257BinaryTreePaths.java | 41 +++++++++++++++++++++++++++++++++++ java/_258AddDigits.java | 16 ++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 java/_257BinaryTreePaths.java create mode 100644 java/_258AddDigits.java diff --git a/java/_257BinaryTreePaths.java b/java/_257BinaryTreePaths.java new file mode 100644 index 0000000..2d93aa3 --- /dev/null +++ b/java/_257BinaryTreePaths.java @@ -0,0 +1,41 @@ +import java.util.List; + +import javax.management.relation.RelationTypeSupport; +import javax.swing.tree.TreeNode; + +/** + * Given a binary tree, return all root-to-leaf paths. + * + * For example, given the following binary tree: + * + * 1 + * / \ + * 2 3 + * \ + * 5 + * All root-to-leaf paths are: + * + * ["1->2->5", "1->3"] + */ + +public class _257BinaryTreePaths { + public List binaryTreePaths(TreeNode root) { + List result = new ArrayList<>(); + if (root != null) { + search(root, "", result); + } + return result; + } + + public void search(TreeNode node, String path, List result) { + if (node.left == null && node.right == null) { + result.add(path + node.val); + } + if (node.left != null) { + search(node.left, path + node.val + "->", result); + } + if (node.right != null) { + search(node.right, path + node.val + "->", result); + } + } +} \ No newline at end of file diff --git a/java/_258AddDigits.java b/java/_258AddDigits.java new file mode 100644 index 0000000..b458fca --- /dev/null +++ b/java/_258AddDigits.java @@ -0,0 +1,16 @@ +/** + * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. + * + * For example: + * + * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. + * + * Follow up: + * Could you do it without any loop/recursion in O(1) runtime? + */ +public class _258AddDigits { + public int addDigits(int num) { + int result = num % 9; + return (result != 0 || num == 0) ? result : 9; + } +} \ No newline at end of file From 2a71961be8f2cc3aec0365d1fc6c4a152a99d46c Mon Sep 17 00:00:00 2001 From: drfish Date: Thu, 30 Nov 2017 20:01:00 +0800 Subject: [PATCH 4/7] Java solution 387 --- java/_387FirstUniqueCharacterinaString.java | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 java/_387FirstUniqueCharacterinaString.java diff --git a/java/_387FirstUniqueCharacterinaString.java b/java/_387FirstUniqueCharacterinaString.java new file mode 100644 index 0000000..33581af --- /dev/null +++ b/java/_387FirstUniqueCharacterinaString.java @@ -0,0 +1,27 @@ +/** + * + * Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. + * + * Examples: + * + * s = "leetcode" + * return 0. + * + * s = "loveleetcode", + * return 2. + * Note: You may assume the string contain only lowercase letters. + */ +public class _387FirstUniqueCharacterinaString { + public int firstUniqChar(String s) { + int[] frequency = new int[26]; + for (int i = 0; i < s.length(); i++) { + frequency[s.charAt(i) - 'a']++; + } + for (int i = 0; i < s.length(); i++) { + if (frequency[s.charAt(i) - 'a'] == 1) { + return i; + } + } + return -1; + } +} \ No newline at end of file From 4b4088dcaf92687f9f2cb73c7f6da2ab1209000d Mon Sep 17 00:00:00 2001 From: drfish <1993sj1993@gmail.com> Date: Thu, 7 Dec 2017 18:43:24 +0800 Subject: [PATCH 5/7] Java solution 274 & 299 --- java/_274H_Index.java | 33 +++++++++++++++++++++++++++++++++ java/_299BullsandCows.java | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 java/_274H_Index.java create mode 100644 java/_299BullsandCows.java diff --git a/java/_274H_Index.java b/java/_274H_Index.java new file mode 100644 index 0000000..1295324 --- /dev/null +++ b/java/_274H_Index.java @@ -0,0 +1,33 @@ +/** + * Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. + * + * According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." + * + * For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. + * + * Note: If there are several possible values for h, the maximum one is taken as the h-index. + */ +public class _274H_Index { + public int hIndex(int[] citations) { + if (citations == null || citations.length == 0) { + return 0; + } + int n = citations.length; + int[] cnts = new int[n + 1]; + for (int citation : citations) { + if (citation >= n) { + cnts[n]++; + } else { + cnts[citation]++; + } + } + int count = 0; + for (int i = n; i >= 0; i--) { + count += cnts[i]; + if (count >= i) { + return i; + } + } + return 0; + } +} \ No newline at end of file diff --git a/java/_299BullsandCows.java b/java/_299BullsandCows.java new file mode 100644 index 0000000..425d3e6 --- /dev/null +++ b/java/_299BullsandCows.java @@ -0,0 +1,38 @@ +/** + * You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number. + * + * For example: + * + * Secret number: "1807" + * Friend's guess: "7810" + * Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.) + * Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. In the above example, your function should return "1A3B". + * + * Please note that both secret number and friend's guess may contain duplicate digits, for example: + * + * Secret number: "1123" + * Friend's guess: "0111" + * In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return "1A1B". + * You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal. + */ +public class _299BullsandCows { + public String getHint(String secret, String guess) { + int a = 0; + int b = 0; + int[] array1 = new int[10]; + int[] array2 = new int[10]; + for (int i = 0; i < secret.length(); i++) { + if (secret.charAt(i) == guess.charAt(i)) { + a++; + } else { + array1[secret.charAt(i) - '0']++; + array2[guess.charAt(i) - '0']++; + } + } + for (int i = 0; i < 10; i++) { + b += Math.min(array1[i], array2[i]); + } + String result = a + "A" + b + "B"; + return result; + } +} \ No newline at end of file From f82d816012298b3c59bfabfa0789da5f26d46fc5 Mon Sep 17 00:00:00 2001 From: drfish <1993sj1993@gmail.com> Date: Fri, 8 Dec 2017 09:59:45 +0800 Subject: [PATCH 6/7] Java solution 273 & 260 --- java/_260SingleNumberIII.java | 29 ++++++++++++++++++ java/_273IntegertoEnglishWords.java | 46 +++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 java/_260SingleNumberIII.java create mode 100644 java/_273IntegertoEnglishWords.java diff --git a/java/_260SingleNumberIII.java b/java/_260SingleNumberIII.java new file mode 100644 index 0000000..6e6b8b0 --- /dev/null +++ b/java/_260SingleNumberIII.java @@ -0,0 +1,29 @@ +/** + * Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. + * + * For example: + * + * Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. + * + * Note: + * The order of the result is not important. So in the above example, [5, 3] is also correct. + * Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? + */ +public class _260SingleNumberIII { + public int[] singleNumber(int[] nums) { + int diff = 0; + for (int num : nums) { + diff ^= num; + } + diff &= -diff; + int[] result = { 0, 0 }; + for (int num : nums) { + if ((num & diff) == 0) { + result[0] ^= num; + } else { + result[1] ^= num; + } + } + return result; + } +} \ No newline at end of file diff --git a/java/_273IntegertoEnglishWords.java b/java/_273IntegertoEnglishWords.java new file mode 100644 index 0000000..5579c4c --- /dev/null +++ b/java/_273IntegertoEnglishWords.java @@ -0,0 +1,46 @@ +import javax.swing.text.AbstractDocument.LeafElement; + +/** + * Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1. + * + * For example, + * 123 -> "One Hundred Twenty Three" + * 12345 -> "Twelve Thousand Three Hundred Forty Five" + * 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" + */ +public class _273IntegertoEnglishWords { + private static final String[] LESS_THAN_20 = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", + "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", + "Nineteen" }; + private static final String[] TENS = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", + "Eighty", "Ninety" }; + private static final String[] THOUSANDS = { "", "Thousand", "Million", "Billion" }; + + public String numberToWords(int num) { + if (num == 0) { + return "Zero"; + } + int i = 0; + String result = ""; + while (num > 0) { + if (num % 1000 != 0) { + result = helper(num % 1000) + THOUSANDS[i] + " " + result; + } + num /= 1000; + i++; + } + return result.trim(); + } + + private String helper(int num) { + if (num == 0) { + return ""; + } else if (num < 20) { + return LESS_THAN_20[num] + " "; + } else if (num < 100) { + return TENS[num / 10] + " " + helper(num % 10); + } else { + return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100); + } + } +} \ No newline at end of file From 92bf28abf81a4cbf988d6595b9e42a6ee1b9071d Mon Sep 17 00:00:00 2001 From: Shen Jie Date: Tue, 19 Mar 2019 22:52:42 +0800 Subject: [PATCH 7/7] Python solution for 207 --- python/207 Course Schedule.py | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 python/207 Course Schedule.py diff --git a/python/207 Course Schedule.py b/python/207 Course Schedule.py new file mode 100644 index 0000000..86cf7b0 --- /dev/null +++ b/python/207 Course Schedule.py @@ -0,0 +1,50 @@ +''' +There are a total of n courses you have to take, labeled from 0 to n-1. + +Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] + +Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? + +Example 1: + +Input: 2, [[1,0]] +Output: true +Explanation: There are a total of 2 courses to take. + To take course 1 you should have finished course 0. So it is possible. +Example 2: + +Input: 2, [[1,0],[0,1]] +Output: false +Explanation: There are a total of 2 courses to take. + To take course 1 you should have finished course 0, and to take course 0 you should + also have finished course 1. So it is impossible. +Note: + + 1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. + 2. You may assume that there are no duplicate edges in the input prerequisites. +''' + + +class Solution: + def canFinish(self, numCourses: int, prerequisites: [[]]) -> bool: + graph = {n: [] for n in range(numCourses)} + for x, y in prerequisites: + graph[x].append(y) + + for target in range(numCourses): + stack = graph[target] + visited = set() + while stack: + course = stack.pop() + visited.add(course) + if course == target: + return False + for i in graph[course]: + if i not in visited: + stack.append(i) + return True + + +if __name__ == "__main__": + assert True == Solution().canFinish(2, [[1, 0]]) + assert False == Solution().canFinish(2, [[1, 0], [0, 1]])