瀏覽標籤:

LinQ

[C#][LeetCode] 804. Unique Morse Code Words

這題要將英文轉換成摩斯密碼,並計算出重複字串的數量,我用 Linq 輕鬆解決。

 

       

[C#][LeetCode][Easy] 561. Array Partition I

問題:

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

心得:
看到這題我第一個反應就是去找linq有沒有辦法分割陣列,然後再加總= =
不過LINQ效能沒有很好,看到最佳解答有提供一個不錯的方法。

我的答案:

最佳解答:

       

[C#][Linq][Expression] 將陣列分割成固定長度的小陣列

來源:[Snippet]在C#中将List分割成多个定长的小List

可以將一個很長很長很長的List分割成固定大小的List方便批次運算。

程式碼:

       

[C#][LeetCode][Easy] 258. 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.

答案:

  1. For + 遞迴
  2. LinQ + 遞迴
  3. Normal
       

[C#][LeetCode][Easy] 242. 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.

答案:

  • LinQ – OrderBy
  • LinQ – Sort
  • Normal – Array.Sort
  • Normal – 硬幹 (會 Time Limit Exceeded)

參考:

  1. (C#)用迴圈印出字母A到Z
       

[C#][LeetCode][Easy] 448. Find All Numbers Disappeared in an Array

心得:

題目大意是有一陣列1~N且亂序,必須找出N並找出未出現哪些數字,剛開始我用硬幹的方式,結果顯示Time Out如下:

後來改用稍為聰明一點的LinQ來找出N,結果還是Time Out如下:

最後生氣了,直接全部都用LinQ,交給RangeExcept直接省略兩個迴圈並且順利解決!

問題:

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

答案:

參考:

  1. [C#] 對List<T>取交集、聯集及差集