您的位置:首页 > 其它

LeetCode刷题记录(第六天)

2018-03-25 22:22 141 查看

Swap Salary

这道题竟然是一个sql题,虽然经常写sql和看关于mysql的性能优化,但是我发现一个大问题,我都白学来。。。。
题目:
Given a table 
salary
, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.
翻译:
给定一个表格
salary
,如下面的表格,其中m =男性,f =女性值。用一个更新查询和没有中间临时表交换所有f和m值(即,将所有f值更改为m,反之亦然)。

事例:

For example:| id | name | sex | salary |
|----|------|-----|--------|
| 1 | A | m | 2500 |
| 2 | B | f | 1500 |
| 3 | C | m | 5500 |
| 4 | D | f | 500 |
After running your query, the above salary table should have the following rows:
| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |
这道题没有什么好讲的,就是一个更新操作赋值时case...when的一个用法,case+要更新的字段,when+条件,then+要更新的值,可以多个链接使用,当然,case...then也可以用在查询中,其他用法可以再去多学习一些。
sql:UPDATE salary
SET
sex = CASE sex
WHEN 'm' THEN 'f'
ELSE 'm'
END;

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.

事例:
Example 1:
Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
Note:

n is a positive integer, which is in the range of [1, 10000].
All the integers in the array will be in the range of [-10000, 10000].
翻译后:
给定一个2n整数的数组,你的任务是将这些整数分成n对整数,例如(a 1,b 1),(a 2,b 2),...,(a n,b n)对于从1到n的所有i ,min(a i,b i)的总和尽可能大。

思路:
读完题目后,思考了一下,想要和最大,首先需要从小到大排序,因为只有从小到大排序后,两个一组中取最小数相加的和最大。而当从小到大排序后,所要相加的数则为第一个、第三个、第五个.....以此类推,所以一步一步想,问题还是能想明白的,就是不知道我这么想有没有什么问题,但是结果还是对的嘛,下面是我的代码:package com.mianshi.suanfa.ArrayPartitionI;

/**
* Created by macbook_xu on 2018/3/25.
*/
public class Solution {
public static int arrayPairSum(int[] nums) {
for (int i = 0 ; i<nums.length ; i++){
for (int j = i+1 ; j<nums.length ; j++){
if(nums[j]<nums[i]){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}

int count = 0;
for (int i = 0 ; i<nums.length ; i+=2){
count += nums[i];
}

return count;
}

public static void main(String[] args) {
int[] nums = {1,4,3,2};
System.out.println(arrayPairSum(nums));
}
}

我现在用的最熟的也只有最简单的冒泡了。。。。虽然学过快速排序啊、插入排序啊什么的,但是没有使用过,还不太熟,最近好好学学排序,下次就不用冒泡丢人了。。。。当然,数组本身也是可以进行排序的,就像下面这个方法:class Solution {
public int arrayPairSum(int[] nums) {
int sum = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i += 2) {
sum += nums[i];
}

return sum;
}
}直接利用数组的排序,然后进行求和,是不是一下觉得更加简单了呢?
今天的这两个题都比较简单,还顺便复习来一下sql,感觉还是不错的,下面是本周的代码整理,以后每周都会往GitHub上这个项目里更新的。
https://github.com/SysWcx/LeetCode
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: