瀏覽標籤:

Easy

[C#][LeetCode][Easy] 657. Judge Route Circle

心得:

控制機器人走路,且最後必須回到起點,把它當作XY軸來理解的話很快就可以解答。
右 X + 1, 左 X – 1, 上 Y + 1, 下 Y – 1,最後 X 與 Y 皆為0則回傳true

問題:

Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.

The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.

Example 1:

Input: "UD"
Output: true

Example 2:

Input: "LL"
Output: false

答案:

public class Solution {
    public bool JudgeCircle(string moves) {
        int x = 0;
        int y = 0;

        foreach (var item in moves)
        {
            switch (item)
            {
                case 'U':
                    {
                        y++;
                        break;
                    }
                case 'D':
                    {
                        y--;
                        break;
                    }
                case 'R':
                    {
                        x++;
                        break;
                    }
                case 'L':
                    {
                        x--;
                        break;
                    }
            }
        }

        return (x == 0 && y == 0);
    }
}

答案 – Linq:

public class Solution {
    public bool JudgeCircle(string moves) {
        int x = moves.Where(p => p == 'U' || p == 'D').Sum(p => (p == 'U') ? 1 : -1);
        int y = moves.Where(p => p == 'R' || p == 'L').Sum(p => (p == 'R') ? 1 : -1);
        return x == 0 && y == 0;
    }
}

 

       

[MySQL][LeetCode][Easy] 595. Big Countries

心得:

這題只要找出領土大於三百萬或是人口大於兩百五十萬的的資料即可

問題:

There is a table World

+-----------------+------------+------------+--------------+---------------+
| name            | continent  | area       | population   | gdp           |
+-----------------+------------+------------+--------------+---------------+
| Afghanistan     | Asia       | 652230     | 25500100     | 20343000      |
| Albania         | Europe     | 28748      | 2831741      | 12960000      |
| Algeria         | Africa     | 2381741    | 37100000     | 188681000     |
| Andorra         | Europe     | 468        | 78115        | 3712000       |
| Angola          | Africa     | 1246700    | 20609294     | 100990000     |
+-----------------+------------+------------+--------------+---------------+

A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million.

Write a SQL solution to output big countries’ name, population and area.

For example, according to the above table, we should output:

+--------------+-------------+--------------+
| name         | population  | area         |
+--------------+-------------+--------------+
| Afghanistan  | 25500100    | 652230       |
| Algeria      | 37100000    | 2381741      |
+--------------+-------------+--------------+

答案:

# Write your MySQL query statement below
SELECT
    name,
    population,
    area
FROM
    World
WHERE
    area > 3000000
OR
    population > 25000000

 

       

[C#][LeetCode][Easy] 535. Encode and Decode TinyURL

題目:

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

心得:

這題實務上的話我應該會用資料庫來存key,簡單易用不是嗎?
不過要小心的是不能使用流水號來當作tinyurl的參數,
這樣會有被猜出key的可能性,可能就隨機產生一個短的字串並檢查不能重複來當key

我的答案(轉base64):

public class Codec {

    // Encodes a URL to a shortened URL
    public string encode(string longUrl) {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(longUrl));
    }

    // Decodes a shortened URL to its original URL.
    public string decode(string shortUrl) {
        return Encoding.UTF8.GetString(Convert.FromBase64String(shortUrl));
    }
}

 

我的答案(guid):

public class Codec {
    
    private static Dictionary<string, string> dty = new Dictionary<string, string>();
    
    // Encodes a URL to a shortened URL
    public string encode(string longUrl) {
        string guid = Guid.NewGuid().ToString();
        dty.Add(guid, longUrl);
        return guid;
    }

    // Decodes a shortened URL to its original URL.
    public string decode(string shortUrl) {
        string url = string.Empty;
        return dty.TryGetValue(shortUrl, out url) ? url : null;
    }
}

 

       

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