1029. 两地调度
公司计划面试 2N 人。第 i 人飞往 A 市的费用为 costs[i][0],飞往 B 市的费用为 costs[i][1]。
返回将每个人都飞到某座城市的最低费用,要求每个城市都有 N 人抵达。
示例:
输入:[[10,20],[30,200],[400,50],[30,20]]
输出:110
解释:
第一个人去 A 市,费用为 10。
第二个人去 A 市,费用为 30。
第三个人去 B 市,费用为 50。
第四个人去 B 市,费用为 20。
最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有一半的人在面试。
提示:
1 <= costs.length <= 100
costs.length 为偶数
1 <= costs[i][0], costs[i][1] <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-city-scheduling
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public class No1029 {
public static void main(String[] args) {
No1029 no1029 = new No1029();
int[][] costs = { { 10, 20 }, { 30, 200 }, { 400, 50 }, { 30, 20 } };
int res = no1029.twoCitySchedCost(costs);
System.out.println(res);
}
public int twoCitySchedCost(int[][] costs) {
// 按照 price_A-price_B的顺序由小到大排序
// 假设2N个人都去B地,再临时改变挑选N个人去A地,这时去B地是本来要付的钱,现在该去A地,那么去B地的钱就是剩余的钱
// 去A地的钱便是要多给的钱,我们让price_A-price_B,可以得出我们要多付的钱,越小越好,取前N个到A地去,剩余的到B地区即可
Arrays.sort(costs, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] - o1[1] - (o2[0] - o2[1]);
}
});
int total = 0;
int n = costs.length / 2;
for (int i = 0; i < n; ++i)
total += costs[i][0] + costs[i + n][1];
return total;
}
}
9. 回文数
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
在看到这道题,我首先想到的是把int数字转化为String字符串,再把String字符串转为数组,根据双指针的思想,从数组的开头和末尾开始比较,只要有不等的,就返回false,知道两个指针相遇。感觉想法挺好的,便用代码实现如下:
package com.czn.easy;
public class No9 {
public static void main(String[] args) {
No9 no9 = new No9();
int x = 121;
boolean res = no9.isPalindrome(x);
System.out.println(res);
}
public boolean isPalindrome(int x) {
// 转化为字符串
String xStr = String.valueOf(x);
// 转化为数组
char[] chars = xStr.toCharArray();
// 标记两个指针
int preIndex = 0;
int sufIndex = chars.length - 1;
// 开始遍历
while (preIndex <= sufIndex) {
if (chars[preIndex++] != chars[sufIndex--]) {
return false;
}
}
return true;
}
}
结果一般般,看看官方的做法:
// 不用把int转化为字符串(进阶解法)
public boolean isPalindrome(int x) {
// 特殊情况:
// 如上所述,当 x < 0 时,x 不是回文数。
// 同样地,如果数字的最后一位是 0,为了使该数字为回文,
// 则其第一位数字也应该是 0
// 只有 0 满足这一属性
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while (x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
// 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。
// 例如,当输入为 12321 时,在 while 循环的末尾我们可以得到 x = 12,revertedNumber = 123,
// 由于处于中位的数字不影响回文(它总是与自己相等),所以我们可以简单地将其去除。
return x == revertedNumber || x == revertedNumber / 10;
}
官方这种做法的优势是不需要将数字转化为字符串再进行操作,是进阶的做法,我就想不到这种做法,挺秒的。