leetcode刷题0515

(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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值