Leetcode | 刷题日记(1)

本文记录个人刷题记录

推荐两个刷题网站:

地址:https://leetcode.com/

另外一个地址:http://www.lintcode.com/

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

题目地址:https://leetcode.com/problems/second-highest-salary/

+----+--------+
| 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 .

解: 

先算出所有员工中最高的工资,然后在从非最高工资中的记录,取最大的一个,就是第二高工资了

select max(Salary) as 'SecondHighestSalary'
from Employee where Salary<(select max(Salary) from Employee)


2. Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

地址:https://leetcode.com/problems/two-sum/

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解:

两层遍历,外层遍历是负责遍历每个元素,内层遍历是用于把当前 外层循环去取出的数与除它之外的元素相加,看是否等于目标数值,如果等于,就返回当前两个元素的索引,如果都没有命中,就返回空数组

public class Solution {
    public int[] twoSum(int[] nums, int target) {
         for(int i=0 ;i<nums.length;i++){
           for(int j=i+1;j<nums.length;j++)
               if (nums[i] + nums[j] == target) {
                   return new int[]{
                       i,j
                   };
               }
       }
      return new int[]{};
    }
}

3. Combine Two Tables

Table: Person

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
+-------------+---------+
PersonId is the primary key column for this table.

Table:  Address

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| AddressId   | int     |
| PersonId    | int     |
| City        | varchar |
| State       | varchar |
+-------------+---------+
AddressId is the primary key column for this table.

Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:
FirstName, LastName, City, State

解:

两个表通过PersonId关联查询即可,但是因为需要有所有Person表记录,所以这里要用leftjoin

SELECT pes.firstName as 'FirstName',
pes.LastName as 'LastName', 
adr.City as 'City', 
adr.State as 'State'
FROM Person pes
LEFT JOIN Address adr
on pes.personid = adr.personid;




猜你喜欢

转载自blog.csdn.net/evan_leung/article/details/52435457