LeetCode-263周赛
真好久没有打比赛了,手感很差...看来力扣还是要刷的,毕竟这种东西刷着是对自己有好处的,锻炼自己的计算机思维。
1.检查句子中的数字是否递增
完全的模拟题,看一眼题目就知道该如何解决,将文字按照空格拆分为各个单词,看该单词是否为数字,如果是 与上一个数字比较是否 更大,如果小 则该句子直接返回false,至到比较到最后一个单词.
时间是:O(N)
空间是:O(1)
class Solution {
public boolean areNumbersAscending(String s) {
String[] strings = s.split(" ");
int num = -1;
for(int i = 0;i < strings.length; i++){
if(strings[i].matches("[0-9]+")){
int n = Integer.parseInt(strings[i]);
if(n > num){
num = n;
}else{
return false;
}
}
}
return true;
}
}
2.简易银行系统
也是一个模拟题,其实比第一题还要简单,就是一个存钱和取钱的操作,只要先看存款够不够取出来,以及不要取到别人的账户的钱就可以
class Bank {
long[] balance;
public Bank(long[] balance) {
this.balance = balance;
}
public boolean transfer(int account1, int account2, long money) {
if(account1 > balance.length || account2 > balance.length){
return false;
}
if(balance[account1-1] < money){
return false;
}
balance[account1-1] = balance[account1-1] - money;
balance[account2-1] = balance[account2-1] + money;
return true;
}
public boolean deposit(int account, long money) {
if(account > balance.length){
return false;
}
balance[account-1] = balance[account-1] + money;
return true;
}
public boolean withdraw(int account, long money) {
if(account > balance.length || balance[account-1] < money){
return false;
}
balance[account-1] = balance[account-1] - money;
return true;
}
}
3.统计按位或能得到最大值的子集数目
是leetcode-46题全排列的一个变式题目,属于中等吧,但做多了也是一个比较简单的题目。
思路:将数字内所有数字的子集可能排列都得到,然后一次进行全部按位或,看有谁比当前的按位或更高,就存那个子集进一个List,如果有更高的出现了就清空List,存最新的数组,最后返回List长度即可。
这里我用了一个递归回溯,来查找所有的子集。当前后面经过对比认真看题,发现测试集的数据其实是不大的,可以用暴力且不用剪纸,直接得到结果。
class Solution {
int allRes = -1;
public int countMaxOrSubsets(int[] nums) {
//递归回溯搜索
if(nums.length == 0){
return 0;
}
List<Integer> res = new ArrayList<Integer>();
List<List<Integer>> list =new ArrayList<List<Integer>>();
back(list ,res, nums, 0);
return list.size();
}
public void back(List<List<Integer>> list ,List<Integer> res,int[] nums, int index){
//如何剔除掉不需要的
for(int i = index; i < nums.length; i++){
res.add(nums[i]);
int sum = res.get(0);
for(int j = 1; j < res.size(); j++){
sum = sum | res.get(j);
}
if(sum > allRes){
allRes = sum;
list.clear();
}
if(sum == allRes){
list.add(new ArrayList<Integer>(res));
}
back(list, res, nums, i+1);
res.remove(res.size()-1);
}
}
}
4.到达目的地的第二短时间
太菜,之前就没做过图的算法题,直接弃了。
总共用了55分钟,第一题5分钟,第二题10分钟,第三题用了40分钟,真的太手生了。总排名1600+,大佬前三题都是10分钟内全A掉的。

浙公网安备 33010602011771号