Below you will find pages that utilize the taxonomy term “LeetCode”
Posts
LeetCode - Missing Number
LeetCode 的 Missing Number 題目如下:
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
簡單的說該方法會被帶入一個陣列,裡面的元素為 0 到 n 不重複的數值,需找到並回傳該陣列缺少的數值。像是如果帶入的陣列是 [0, 1, 3],該陣列跳過了 2,所以回傳值會是 2。
因為長度為 n 的陣列如果沒有跳號,裡面的元素應該是 0, …, n,且缺少的數值只有一個。所以我們可以把帶入的陣列跟本來預期的值相減後加總,然後用陣列的長度與之相減。
read morePosts
LeetCode - Move Zeroes
LeetCode 的 Move Zeroes 題目如下:
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.
read morePosts
LeetCode - Number of 1 Bits
LeetCode 的 Number of 1 Bits 題目如下:
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
簡單的說就是給予一個整數,回傳該數值用二進制表示時有多少個 1。
這邊我們可以用 while 迴圈持續的用 n-1 去做 and 運算,並計算運行次數,直至 n 變為 0。
public class Solution { public int HammingWeight(uint n) { int count = 0; while(n > 0) { n &= (n-1); ++count; } return count; } } {% img /images/posts/NumberOf1Bits/1.
read morePosts
LeetCode - Power of Three
LeetCode 的 Power of Three 題目如下:
Given an integer, write a function to determine if it is a power of three.
簡單說他要的是要一個功能,給予一個整數,能判別是否為 3 的冪次。
這邊我們只要判斷數值是否大於零,且是否可整除 1162261467 即可。1162261467 是來自 3^19,為最大的 3 冪次整數,如果某數值可以將之整除,即代表該數值為 3 的冪次。
public class Solution { public bool IsPowerOfThree(int n) { return n > 0 && 1162261467 % n == 0; } } {% img /images/posts/PowerOfThree/1.png %}
Link Power of Three | LeetCode OJ
read morePosts
LeetCode - Add Digits
LeetCode 的 Add Digits 題目如下:
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.
簡單的說就是給予一個整數,反覆的將每個位數值加總,直至數值只有一個位數為止。
最直覺得解法就是用迴圈下去處理,判斷數值是否大於等於 10,如果大於等於 10,則將每個位數的數值加總取代本來的數值。如果數值小於 10,則直接將數值回傳。
public class Solution { public int AddDigits(int num) { var value = num; while(value >= 10) { var originalValue = value; var newValue = 0; do { newValue += originalValue / 10; originalValue = originalValue % 10; }while(originalValue >= 10); newValue += originalValue; value = newValue; } return value; } } {% img /images/posts/AddDigits/1.
read morePosts
LeetCode - Happy Number
LeetCode 的 Happy Number 題目如下:
Write an algorithm to determine if a number 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, and 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 numbers.
read morePosts
LeetCode - Roman to Integer
LeetCode 的 Roman to Integer 題目如下:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
簡單的說他是要一個功能,當給予一個羅馬數字,能將它轉換成對應的數值。
這需要參考 羅馬數字 - 維基百科,自由的百科全書,看羅馬數字背後的規則。
羅馬數字有七個字母組成,分別為 I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和 M(1000)。當字母重複出現,則表示數值為重複倍。如果較大的字母右邊放上較小的字母,表示兩數要相加,反之表示大數要減小數。其它的規則跟這題無關,就不提了。
所以像是 4 對應到的就是 IV (5 - 1),XX 對應到 20 (10 + 10), VIII 對應到 8 (5 + 1 + 1 + 1),以此類推。
這邊筆者是用一個字典檔存放羅馬數字字元與其對應的數值,從輸入參數的後面往前處理,如果前一個字元對應到的數值大於現在這字元的數值,則將回傳值減去當前數值,反之則加上當前數值。
public class Solution { public int RomanToInt(string s) { var dict = new Dictionary<char, int>() { {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}, }; var ret = 0; var prev = -1; for(var idx = s.
read morePosts
LeetCode - Length of Last Word
LeetCode 的 Length of Last Word 題目如下:
Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = “Hello World”,
return 5.
簡單說他要的是要一個功能,當給予一個由大小寫字元與空字元所組成的字串,會回傳最後一個 Word 的長度。
如果最後一個 Word 不存在,則回傳0。
舉個例子來說:
給予 “Hello World”, 會回傳 5.
read morePosts
LeetCode - Power of Two
LeetCode 的 Power of Two 題目如下:
Given an integer, write a function to determine if it is a power of two.
簡單說他要的是要一個功能,給予一個整數,能判別他是否是 2 的冪次。
可以簡單的用迴圈反覆的除以 2,看是否可以整除。
public class Solution { public bool IsPowerOfTwo(int n) { if (n == 0) return false; if (n == 1) return true; var mod = -1; do { mod = n % 2; n /= 2; } while(n != 1 && mod == 0); return n == 1 && mod == 0; } } 也可以用位元運算下去處理,寫起來會更為簡潔,像是這樣:
read morePosts
LeetCode - Valid Anagram
LeetCode 的 Valid Anagram 題目如下:
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Note:
You may assume the string contains only lowercase alphabets.
簡單說他要的是要一個功能,當給予兩個字串,能判斷出這兩個字串是否只是不同的組合順序。
舉個例子來說, s = “anagram”, t = “nagaram”, 回傳 ture.
s = “rat”, t = “car”, 回傳 false.
這邊我們可以統計兩個字串中的每個字元出現的個數是否一樣,也可以像筆者這樣簡單的將字串排序後直接比對。
read morePosts
LeetCode - Plus One
LeetCode 的 Plus One 題目如下:
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
簡單說他要的是要一個類似加法器的功能。給予一個非負的數值陣列用以表示一個非負的數值,能回傳加一後的數值。
這邊筆者是用 for 迴圈從輸入的陣列尾端往前遍巡,第一個處理的陣列元素加一後如果有超過 10,則將當前數值改為除 10 後的餘數,且進位的值帶到下一個陣列數值去做相同的處理。最後跑完如果無進位值,則把當前處理完的陣列回傳。若有進位值,則將進位值與當前處理完的陣列合併回傳。
public class Solution { public int[] PlusOne(int[] digits) { var carry = 1; var result = new int[digits.Length]; for(var idx = digits.Length - 1; idx >= 0; --idx) { var digit = digits[idx]; var newDigit = digit + carry; carry = newDigit / 10; result[idx] = newDigit % 10; } if(carry == 0) return result; return (new int[]{carry}).
read morePosts
LeetCode - Valid Parentheses
LeetCode 的 Valid Parentheses 題目如下:
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
簡單說他要的是要一個功能,帶入的字串只會由 ‘(’、’)’、’{’, ‘}’、’[’ 與 ‘]’ 這幾個字元所組成,需判斷輸入是否正確。
輸入的字元需成對並符合一定的順序,成對的字元內不可夾雜不成對的字元,像是 “()” 與 “()[]{}” 就是正確的格式,而 “(]” 與 “([)]” 不是。
這邊筆者是用 Dictionary 去紀錄成對的字元。然後將帶入的字串字元依序處理。如果其字元跟堆疊最後的字元成對,則將堆疊最後的字元取出。若不成對則將當前字元放入堆疊內。
堆疊在使用前會先放一個空的字元,如果處理到最後堆疊內還剩一個字元,代表帶入的字串是正確的,反之則帶入的字串是錯誤的。
public class Solution { public bool IsValid(string s) { var validChars = new Dictionary<char, char>() { {'(', ')'}, {'{', '}'}, {'[', ']'} }; var length = s.
read morePosts
LeetCode - Contains Duplicate III
LeetCode 的 Contains Duplicate III 題目如下:
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
簡單說他要的是要一個功能,當給予一個整數陣列,能找出兩個不同的索引值,這兩個索引值的差距最多為 k,且這兩個索引值對應整數陣列所得到的整數值相差最多為 t。
這邊筆者是用迴圈搭配 Dictionary 來處理,Dictionary 內只存放 k 筆資料,每次處理一個數值時就去查看 Dictionary 內是否有相差 t 的數值。 如果有則去判斷索引值的差距是否在 k 內,是的話則回傳 true。
public class Solution { public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) { var length = nums.
read morePosts
LeetCode - Contains Duplicate II
LeetCode 的 Contains Duplicate II 題目如下:
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
簡單說他要的是要一個功能,當給予一個整數陣列與一個整數值 k,能找出兩個不同的索引值,這兩個索引值的差距最多為 k,且其對應到的整數陣列的值是相同的。
這邊筆者是用迴圈搭配 Dictionary 來處理,每跑一個數就去判斷 Dictionary 是否有含有一樣的數值,如果有則去判斷索引值的差距是否在 k 內,是的話則回傳 true。如果不是或是數值不存在在 Dictionary 內,則將其加入或是將 Dictionary 中的索引值更新,便於後續查找。如果整個陣列跑完都找不到結果,將 false 回傳。
public class Solution { public bool ContainsNearbyDuplicate(int[] nums, int k) { var length = nums.
read morePosts
LeetCode - Contains Duplicate
LeetCode 的 Contains Duplicate 題目如下:
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
簡單說他要的是要一個功能,當給予一個整數陣列,能找出陣列中是否有重複的數值。如果有重複則方法回傳 true,如果沒有重複則回傳 false。
這邊筆者是用迴圈搭配 HashSet 來處理,每跑一個數就去判斷 HashSet 是否有重複的資料,有則回傳 true,沒有則加到 HashSet 中。
public class Solution { public bool ContainsDuplicate(int[] nums) { var length = nums.Length; var hs = new HashSet<int>(); for(var idx = 0; idx < length; ++idx) { var num = nums[idx]; if(hs.
read more