瀏覽標籤:

Easy

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

 

       

[MySQL][LeetCode][Medium] 184. Department Highest Salary

心得

題目要求找出每個部門薪水最高的員工,若同部門最高薪水有複數則一起顯示,這題我在JOIN部門清單的時候先去把各部門最高薪資數字先撈了出來,這樣在關聯兩張表的時候就可以直接搜尋員工薪水是否等於最高薪資。

問題

The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.

+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
+----+-------+--------+--------------+

The Department table holds all departments of the company.

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department.

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| Sales      | Henry    | 80000  |
+------------+----------+--------+

答案

  1. JOIN部門清單的時候先去把各部門最高薪資數字先撈了出來
    # Write your MySQL query statement below
    SELECT  b.Name AS Department,
            a.Name AS Employee,
            a.Salary AS Salary
    FROM Employee AS a
    JOIN (  SELECT z.*, (SELECT MAX(y.Salary)
                         FROM Employee AS y
                         WHERE z.Id = y.DepartmentId
                         LIMIT 0, 1) AS MaxSalary
            FROM Department AS z) AS b
    ON a.DepartmentId = b.Id AND a.Salary = b.MaxSalary
  2. (2017/01/16) 寫 185. Department Top Three Salaries 時後發現的方法
    # Write your MySQL query statement below
    SELECT  b.Name AS Department,
            a.Name AS Employee,
            a.Salary AS Salary
    FROM Employee AS a
    JOIN Department AS b
    ON a.DepartmentId = b.Id
    WHERE ( SELECT COUNT(DISTINCT(z.Salary)) 
            FROM Employee AS z
            WHERE a.DepartmentId = z.DepartmentId
            AND a.Salary < z.Salary) = 0
       

[MySQL][LeetCode][Easy] 196. Delete Duplicate Emails

心得

題目要求刪除同樣Email的資料,在DELETE的條件WHERE裡面不能包含異動的表(Person),所以這裡再包了一層SELECT來排除編譯錯誤的問題,而這層必須給予別名(強制)否則會編譯錯誤。

問題

Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | [email protected] |
| 2  | [email protected]  |
| 3  | [email protected] |
+----+------------------+
Id is the primary key column for this table.

For example, after running your query, the above Person table should have the following rows:

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | [email protected] |
| 2  | [email protected]  |
+----+------------------+

答案

DELETE 
FROM    Person
WHERE   Id 
NOT IN (SELECT y.*
        FROM (  SELECT MIN(z.Id)
                FROM Person AS z
                GROUP BY z.Email) AS y)

 

       

[MySQL][LeetCode][Easy] 197. Rising Temperature

心得

題目要求找出溫度比前一天高的資料,這裡用了DATE_SUBTO_DAYS兩種方式來解答。

題目

Given a Weather table, write a SQL query to find all dates’ Ids with higher temperature compared to its previous (yesterday’s) dates.

+---------+------------+------------------+
| Id(INT) | Date(DATE) | Temperature(INT) |
+---------+------------+------------------+
|       1 | 2015-01-01 |               10 |
|       2 | 2015-01-02 |               25 |
|       3 | 2015-01-03 |               20 |
|       4 | 2015-01-04 |               30 |
+---------+------------+------------------+

For example, return the following Ids for the above Weather table:

+----+
| Id |
+----+
|  2 |
|  4 |
+----+

答案

  1. Sub Query
    # Write your MySQL query statement below
    SELECT  a.Id
    FROM    Weather AS a
    WHERE   (   SELECT  z.Temperature
                FROM    Weather AS z
                WHERE   DATE_SUB(a.Date, INTERVAL 1 DAY) = z.Date) < a.Temperature
  2. Join
    # Write your MySQL query statement below
    SELECT  a.Id
    FROM    Weather AS a
    JOIN    Weather AS b
    ON      DATE_SUB(a.Date, INTERVAL 1 DAY) = b.Date
    WHERE   a.Temperature > b.Temperature
  3. TO_DAYS
    # Write your MySQL query statement below
    SELECT  a.Id
    FROM    Weather AS a
    JOIN    Weather AS b
    ON      TO_DAYS(a.Date) - TO_DAYS(b.Date) = 1
    WHERE   a.Temperature > b.Temperature

     

參考:

  1. DATE_ADD() 與 DATE_SUB() 日期的加法與減法
  2. Mysql日期和時間函數不求人
       

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

[MySQL][LeetCode][Easy] 183. Customers Who Never Order

心得

這題要show出沒有訂過東西的客戶,所以可以使用LEFT JOIN來關聯兩張表。

問題

Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.

Table: Customers.

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

Table: Orders.

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

Using the above tables as example, return the following:

+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

答案

  1. LEFT JOIN
    # Write your MySQL query statement below
    SELECT      a.Name AS Customers
    FROM        Customers AS a
    LEFT JOIN   Orders AS b
    ON          a.Id = b.CustomerId
    WHERE       b.CustomerId IS NULL
  2. Sub Query
    # Write your MySQL query statement below
    SELECT  a.Name AS Customers
    FROM    Customers AS a
    WHERE   (   SELECT  COUNT(1)
                FROM    Orders AS z
                WHERE   z.CustomerId = a.Id) = 0
       

[MySQL][LeetCode][Easy] 176. Second Highest Salary

心得:

找出該資料表內第二高薪水的筆數,若無則回傳null。

問題:

Write a SQL query to get the second highest salary from the Employee table.

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return null.

答案:

  1. Sub Query
    # Write your MySQL query statement below
    SELECT  MAX(a.Salary) AS SecondHighestSalary
    FROM    Employee AS a
    WHERE   a.Salary < (SELECT  MAX(z.Salary)
                        FROM    Employee AS z)
  2. DISTINCT > 不重複
    # Write your MySQL query statement below
    SELECT
    (
        SELECT DISTINCT Salary
        FROM            Employee
        ORDER BY        Salary DESC
        LIMIT           1, 1
    ) AS SecondHighestSalary
  3. GROUP BY > 不重複
    # Write your MySQL query statement below
    SELECT
    (
        SELECT          Salary
        FROM            Employee
        GROUP BY        Salary
        ORDER BY        Salary DESC
        LIMIT           1, 1
    ) AS SecondHighestSalary