瀏覽標籤:

LeetCode

[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效能沒有很好,看到最佳解答有提供一個不錯的方法。

我的答案:

public class Solution {
    public int ArrayPairSum(int[] nums) {
        return nums.OrderBy(x => x)
                   .Select((x, index) => new { index, x })
                   .GroupBy(x => x.index / 2)
                   .Sum(x => x.Select(y => y.x).Min());
    }
}

最佳解答:

public class Solution {
    public int ArrayPairSum(int[] nums) {
        Array.Sort(nums);
        int result = 0;
        for (int i = 0; i < nums.Length; i += 2)
        {
            result += nums[i];
        }
        return result;
    }
}
       

[C#][LeetCode][Easy] 617. Merge Two Binary Trees

問題:

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

心得:

這題就是把兩個二元樹合併,我就想著最簡單遞迴來解決,看了最佳解答才發現如果為一邊null的話就可以直接用另外一邊來return更有效率,學習了。
我的答案:

public class Solution {
    public TreeNode MergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null && t2 == null)
        {
            return null;
        }

        int t1Val = (t1 == null) ? 0 : t1.val;
        int t2Val = (t2 == null) ? 0 : t2.val;

        return new TreeNode(t1Val + t2Val)
        {
            left = MergeTrees(t1?.left, t2?.left),
            right = MergeTrees(t1?.right, t2?.right)
        };
    }
}

最佳解答:

public class Solution {
    public TreeNode MergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null)
        {
            return t2;
        }
        if (t2 == null)
        {
            return t1;
        }

        return new TreeNode(t1.val + t2.val)
        {
            left = MergeTrees(t1.left, t2.left),
            right = MergeTrees(t1.right, t2.right)
        };
    }
}

 

       

[C#][LeetCode][Easy] 167. Two Sum II – Input array is sorted

心得

這題我本來是想用兩個for迴圈解決的

public class Solution {
    public int[] TwoSum(int[] numbers, int target) {
        for (int i = 0; i < numbers.Length; i++)
        {
            for (int j = numbers.Length - 1; j > i; j--)
            {
                if (numbers[i] + numbers[j] == target)
                {
                    return new int[] { i + 1, j + 1 };
                }
            }
        }

        throw new Exception();
    }
}

但發現會Time Limit Exceeded於是乎看了一下Solutions他們是用一個while迴圈來解答,題目要求index1<index2且不能使用重複的元素,所以這題如果用while的話宣告兩個變數分別是left與right就可以只用一個迴圈就解決。

問題

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

答案

public class Solution {
    public int[] TwoSum(int[] numbers, int target) {
        int left = 0;
        int right = numbers.Length - 1;
        while (numbers[left] + numbers[right] != target)
        {
            if (numbers[left] + numbers[right] > target)
            {
                right--;
            }
            else
            {
                left++;
            }
        }

        return new int[] { left + 1, right + 1 };
    }
}

 

       

[C#][LeetCode][Easy] 409. Longest Palindrome

心得

獲得字串並判斷字串內的字母能組成最長的回文大小為多少,例如傳入asdasdAAAvzxh則答案為9,字串為asdAvAdsa,其中v可替換成任意一位使用字母。

問題

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

答案

public class Solution {
    public int LongestPalindrome(string s) {
        int ans = 0;
        int[] lower = new int[26];
        int[] upper = new int[26];
        foreach (var item in s)
        {
            if (item > 'Z')
            {
                lower[item - 'a']++;
            }
            else
            {
                upper[item - 'A']++;
            }

        }
        for (int i = 0; i < lower.Length; i++)
        {
            ans += lower[i] / 2;
            ans += upper[i] / 2;
        }

        ans = ans * 2;
        return ans < s.Length ? ans + 1 : ans;
    }
}

 

       

[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;
    }
}