Leetcode刷题
来源:互联网 发布:方知浮生未歇什么意思 编辑:程序博客网 时间:2024/06/07 12:46
485.Max Consecutive Ones
Description
Given a binary array, find the maximum number of consecutive 1s in this array.
给定一个二进制数组,找出这个数组中最大的连续1的个数
public class Solution { public int findMaxConsecutiveOnes(int[] nums) { int maxNumber = 0,number = 0; int len = nums.length; //遇0则变0,遇1则加1 for(int i = 0;i < len; i++){ if(nums[i] == 0){ number = 0; } else{ number++; if(maxNumber < number) maxNumber = number; } } return maxNumber; }}public class Solution { public int findMaxConsecutiveOnes(int[] nums) { int maxNumber = 0,number = 0; int len = nums.length; //遇1则加1,遇0则变0 for(int i = 0;i < len; i++){ if(nums[i] == 1){ number ++; } else{ if(number > maxNumber){ maxNumber = number; } number = 0; } } //注意num[len - 1]如果是1的话没有执行给maxNumber赋值的语句 if(number >maxNumber){ maxNumber = number; } return maxNumber; }}
461. Hamming Distance
Description
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
给定两个整数,求其对应二进制位上是不同数字的个数。
public int hammingDistance(int x, int y) { int distance = 0; int k = x ^ y; //调用Integer类中的bitcount方法求一个整数的二进制中1的个数 distance = Integer.bitCount(k); return distance; }public int hammingDistance(int x, int y) { int distance = 0; int k = x ^ y; System.out.println(k); while(k != 0){ //和1相与,结果为1则最低位为1,结果为0则最低位为0 if( (k & 1) == 1) distance ++; k = k >> 1;//右移 } return distance;}
//逐位异或public int hammingDistance(int x, int y) { int distance = 0; while(x !=0 || y!=0){ if(((x & 1) ^ (y & 1)) == 1){ distance ++; } x = x >> 1; y = y >> 1; } return distance; }
//(借鉴)利用递归 public int hammingDistance(int x, int y) { if((x ^ y) == 0) return 0; return (x ^ y) % 2 + hammingDistance(x >> 1, y >> 1); }
感想:1. 二进制位运算要充分利用二进制运算符,~,&,|,^(异或,相同为0,不同为1)
2. 巧妙利用递归简化代码
0 0
- 【LeetCode】Leetcode刷题 笔记
- leetcode 刷题
- LeetCode刷题
- LeetCode刷题
- Leetcode刷题
- leetcode刷题
- Leetcode刷题
- leetcode刷题
- 【leetcode】leetcode 刷题 笔记 (不定期更新)
- leetcode刷题 开始篇
- leetcode 刷题:LRU cache
- leetcode刷题:atoi
- Leetcode OJ 刷题
- Sort List leetcode刷题
- leetcode 刷题ing
- LeetCode刷题 | Add Binary
- LeetCode刷题 | Climbing Stairs
- [LeetCode刷题] Word Ladder
- DTLS-PSK算法抓包解析_0
- Spring MVC参数传递中文乱码解决方案
- MVVM的详细讲解
- 最详细的Log4j使用教程
- [leetcode]--26. Remove Duplicates from Sorted Array
- Leetcode刷题
- LeetCode | GrayCode
- 编程相关——RMI
- 测试
- jeesite快速开发平台(二)----环境搭建
- thymeleaf 获取map的值
- hdu1030【找规律】
- 同步和异步的概念
- DTLS-PSK算法抓包解析_1