(485)最大连续1的个数
实现
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0, max = 0;
for(int i = 0; i < nums.length;i++){
if(nums[i] == 1){
count++;
max = Math.max(count,max);
}else{
count = 0;
}
}
return max;
}
}
(595)大的国家
实现
select
name,population,area
from
World
where
area > 3000000 or population > 25000000
;
也可以使用UNION
连接子查询
(260)只出现一次的数字
实现
思路:最初的想法是先将nums进行排序,i首先指向数组开头,j指向其下一位。如果j的值和i的值相等,则表明nums[i]和nums[j]的值相同,将i=j+1,j=i+1;否则的话,先将nums[i]放入res[]中,i++,j++。
class Solution {
public static int[] singleNumber(int[] nums) {
Arrays.sort(nums);
int res[] = new int[2];
int i = 0;
int j = 1;
int k = 0;
while(i < nums.length && j < nums.length) {
if(nums[i] == nums[j]) {
i = j + 1;
if(j == nums.length - 1) {
res[k] = nums[j];
k++;
}
}else {
res[k] = nums[i];
k++;i++;
//处理最后一个元素
if(j == nums.length - 1) {
res[k] = nums[j];
k++;
j++;
}else {
j++;
}
}
}
return res;
}
}
但是提交后超出时间限制,算法太辣鸡。分析原因主要是使用了sort()消耗大量的时间。本题可以使用HashMap,异或值来解决,可以看看官方给出的解答。
自己试着用HashMap实现如下。思路就是先将数组中的值放入hashmap中记录出现的次数,最后取出值为1的放入res[]中。
class Solution {
public int[] singleNumber(int[] nums) {
int[] res = new int[2];
int i = 0;
HashMap<Integer, Integer> hashmap = new HashMap<>();
for(int num : nums){
hashmap.put(num, hashmap.getOrDefault(num, 0) + 1);
}
for(Map.Entry<Integer, Integer> entry : hashmap.entrySet()){
if(entry.getValue() == 1){
res[i++] = entry.getKey();
}
}
return res;
}
}