瀏覽標籤:

C#

[C#][LeetCode][Easy] 349. Intersection of Two Arrays

心得

題目要求找出兩個int[]交集的數字有哪些且不能重複並輸出。

問題

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

答案

  1. .NET提供的方法
    public class Solution {
        public int[] Intersection(int[] nums1, int[] nums2) {
            return nums1.Intersect(nums2).ToArray();
        }
    }
  2. 上面那個方法太賤了,於是乎自己硬幹了一次
    public class Solution {
        public int[] Intersection(int[] nums1, int[] nums2) {
            List<int> list = new List<int>();
            Array.Sort(nums1);
            Array.Sort(nums2);
            for (int i = 0; i < nums1.Length; i++)
            {
                for (int j = 0; j < nums2.Length; j++)
                {
                    if (nums1[i] == nums2[j])
                    {
                        if (list.Count == 0 || list[list.Count - 1] < nums1[i])
                        {
                            list.Add(nums1[i]);
                        }
                        break;
                    }
                }
            }
    
            return list.ToArray();
        }
    }

     

       

[C#][LeetCode][Easy] 383. Ransom Note

心得

這題要比對字串變數ransomNote是否存在於字串變數magazine裡。

問題

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom
note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:
You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

答案

  1. 先將所有字母的數量統計在比較
    public class Solution {
        public bool CanConstruct(string ransomNote, string magazine) {
            if (ransomNote.Length > magazine.Length)
            {
                return false;
            }
    
            Dictionary<char, int> dty_1 = getCharCount(ransomNote);
            Dictionary<char, int> dty_2 = getCharCount(magazine);
    
            foreach (var item in dty_1)
            {
                int tmp = 0;
                if (!dty_2.TryGetValue(item.Key, out tmp) || item.Value > tmp)
                {
                    return false;
                }
            }
    
    
            return true;
        }
        
        private Dictionary<char, int> getCharCount(string str)
        {
            Dictionary<char, int> dty = new Dictionary<char, int>();
    
            while (str.Length > 0)
            {
                dty.Add(str[0], str.Count(x => x == str[0]));
                str = str.Replace(str[0].ToString(), "");
            }
    
            return dty;
        }
    }
  2. 方法1的簡化版
    public class Solution {
        public bool CanConstruct(string ransomNote, string magazine) {
            if (ransomNote.Length > magazine.Length)
            {
                return false;
            }
    
            while (ransomNote.Length > 0)
            {
                if (ransomNote.Count(x => x == ransomNote[0]) > magazine.Count(x => x == ransomNote[0]))
                {
                    return false;
                }
    
                ransomNote = ransomNote.Replace(ransomNote[0].ToString(), "");
            }
    
            return true;
        }
    }
  3. 這方法是在解答內看到的,解題思路與方法1差不多但是速度快了很多。
    public class Solution {
        public bool CanConstruct(string ransomNote, string magazine) {
            if (ransomNote.Length > magazine.Length)
            {
                return false;
            }
        
            int[] table = new int[26];
            foreach (var item in magazine)
            {
                table[item - 'a']++;
            }
            foreach (var item in ransomNote)
            {
                table[item - 'a']--;
                if (table[item - 'a'] < 0)
                {
                    return false;
                }
            }
        
            return true;
        }
    }

     

       

[C#][LeetCode][Easy] 500. Keyboard Row

心得

鍵盤共有三行[qwertyuiop, asdfghjkl, zxcvbnm],找出在同行字母拼湊出來的單字。

問題

Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.

keyboard

 

Example 1:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

答案

public class Solution {
    public string[] FindWords(string[] words) {
        string row_1 = "qwertyuiop";
        string row_2 = "asdfghjkl";
        string row_3 = "zxcvbnm";

        return words.Where(x =>
        {
            var str = x.ToLower().ToArray();
            return !str.Any(y => !row_1.Contains(y)) || !str.Any(y => !row_2.Contains(y)) || !str.Any(y => !row_3.Contains(y));
        }).ToArray();
    }
}
       

[C#][LeetCode][Easy] 455. Assign Cookies

心得

題目詢問說共可以滿足幾個小孩所期望的蛋糕數,例如總共有三個小孩A, B, C,A希望獲得1片蛋糕;B希望獲得2片蛋糕;C希望獲得3片蛋糕,而總共有兩塊蛋糕Z, X,Z可以切成1片,X可以切成兩片,這樣的話答案是2,因為最多只能滿足兩個小孩的需求。依照這個思路去撰寫Code就容易得多了。

問題

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

Note:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.

Example 1:

Input: [1,2,3], [1,1]

Output: 1

Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. 
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.

Example 2:

Input: [1,2], [1,2,3]

Output: 2

Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. 
You have 3 cookies and their sizes are big enough to gratify all of the children, 
You need to output 2.

答案

public class Solution {
    public int FindContentChildren(int[] g, int[] s) {
        Array.Sort(g);
        Array.Sort(s);

        int ans = 0;

        for (int i = 0; ans < g.Length && i < s.Length; i++)
        {
            if (g[ans] <= s[i])
            {
                ans++;
            }
        }
        
        return ans;
    }
}

 

       

[C#][LeetCode][Easy] 492. Construct the Rectangle

心得

簡單來說就是輸入數字x,找出x的因數並找出相乘會等於x的兩個數字且兩數字相減最接近0的組合,大的放前面小的放後面以int[]的型態回傳。

問題

For a web developer, it is very important to know how to design a web page’s size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:

1. The area of the rectangular web page you designed must equal to the given target area.

2. The width W should not be larger than the length L, which means L >= W.

3. The difference between length L and width W should be as small as possible.

You need to output the length L and the width W of the web page you designed in sequence.

Example:

Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. 
But according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.

Note:

  1. The given area won’t exceed 10,000,000 and is a positive integer
  2. The web page’s width and length you designed must be positive integers.

答案

  1. 我的笨方法
    public class Solution {
        public int[] ConstructRectangle(int area) {
            int num1 = Enumerable
                .Range(1, (int)Math.Sqrt(area))
                .Where(x => area % x == 0)
                .OrderBy(x => Math.Abs((area / x) - x))
                .FirstOrDefault();
            int num2 = area / num1;
            return num1 > num2 ? new int[] { num1, num2 } : new int[] { num2, num1 };
        }
    }
  2. Top Solution的神方法
    public class Solution {
        public int[] ConstructRectangle(int area) {
            int w = (int)Math.Sqrt(area);
            while( area % w != 0){
                w--;
            }
            return new int[] { area / w, w };
        }
    }

     

       

[C#][LeetCode][Easy] 485. Max Consecutive Ones

心得

傳入一個二進位的陣列,找出1最多連續出現的次數。

問題

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.

Note:

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

答案

public class Solution {
    public int FindMaxConsecutiveOnes(int[] nums) {
        int maxcount = 0, count = 0;
        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] == 1)
            {
                count++;
            }
            else
            {
                if (maxcount < count)
                {
                    maxcount = count;
                }
                count = 0;
            }
        }
        return maxcount < count ? count : maxcount;
    }
}

 

       

[C#][LeetCode][Easy] 27. Remove Element

心得

[C#][LeetCode][Easy] 283. Move Zeroes 有87% 像。

問題

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

答案

public class Solution {
    public int RemoveElement(int[] nums, int val) {
        int j = 0;
        for(int i = 0; i < nums.Length; i++){
            if(nums[i] != val){
                nums[j] = nums[i];
                j++;
            }
        }
        
        return j;
    }
}

 

       

[C#][LeetCode][Easy] 283. Move Zeroes

心得

將數字陣列中為零的數字在不更動其他數字排序的情況下移至陣列最後方,這題要求必須使用原陣列不能new一個新的物件就比較麻煩一點點了。

問題

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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

答案

public class Solution {
    public void MoveZeroes(int[] nums) {
        int j = 0;
        for(int i = 0; i < nums.Length; i++){
            if(nums[i] != 0){
                nums[j] = nums[i];
                j++;
            }
        }
        
        for(int i = j; i < nums.Length; i++){
            nums[i] = 0;
        }
    }
}
       

[C#][LeetCode][Easy] 476. Number Complement

心得:

題目要求將數字轉換為其補數,看起來滿單純的我就想不開硬幹了,由於不想借助C#內建的方法,所以自己實作二進位與十進位之間轉換。

題目:

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.

答案:

  1. Normal – 硬幹
    public class Solution {
        public int FindComplement(int num) {
            string str = ConvertMethod(num);
            string ans = "";
            for(int i = 0; i < str.Length; i++){
                if(str[i] == '0'){
                    ans += "1";
                }else{
                    ans += "0";
                }
            }
            
            return ConvertMethod(ans);
        }
        
        private string ConvertMethod(int num){
            string str = "";
            while (num > 1)
            {
                str = num % 2 + str;
                num = num / 2;
                if (num == 1)
                {
                    str = num + str;
                    num = 0;
                }
            }
            
            return str;
        }
        
        private int ConvertMethod(string str)
        {
            int ans = 0;
            for (int i = 0; i < str.Length; i++)
            {
                int tmp = 1;
                for (int j = 1; j < (str.Length - i); j++)
                {
                    tmp *= 2;
                }
                ans += tmp * int.Parse(str[i].ToString());
            }
    
            return ans;
        }
    }
  2. LinQ
    public class Solution {
        public int FindComplement(int num) {
            return Convert.ToInt32(new string(Convert.ToString(num, 2).Select(x => x == '1' ? '0' : '1').ToArray()), 2);
        }
    }

參考:

  1. http://www.sggs.hc.edu.tw/sggsnew/comp/bccto2816.htm
  2. [C#] 轉2進位 / 10進位 / 16進位
       

[C#][LeetCode][Easy] 226. Invert Binary Tree

心得:

這題也是典型的遞迴,題目要求把二元樹整個翻轉過來。

問題:

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

to

     4
   /   \
  7     2
 / \   / \
9   6 3   1

答案:

  1. 遞迴
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode InvertTree(TreeNode root) {
            if(root == null){
                return null;
            }
            
            var left = root.left;
            var right = root.right;
            root.left = InvertTree(right);
            root.right = InvertTree(left);
            
            return root;
        }
    }