169. 多数元素
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
//摩尔投票法
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
Integer candidate = null;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}
- 投票算法证明:
- 如果候选人不是maj 则 maj,会和其他非候选人一起反对 会反对候选人,所以候选人一定会下台(maj==0时发生换届选举)
- 如果候选人是maj , 则maj 会支持自己,其他候选人会反对,同样因为maj 票数超过一半,所以maj 一定会成功当选
1108. IP 地址无效化
class Solution {
public String defangIPaddr(String address) {
String[] splits = address.split("\\.");
StringBuffer stringBuffer = new StringBuffer();
for (String split : splits) {
stringBuffer.append(split + "[.]");
}
return stringBuffer.toString().substring(0, stringBuffer.length() - 3);
}
}
class Solution {
public String defangIPaddr(String address) {
return address.replace(".","[.]");
}
}
1351. 统计有序矩阵中的负数
class Solution {
public int countNegatives(int[][] grid) {
int output = 0;
for (int i=0; i<grid.length; i++) {
for (int j=grid[0].length-1; j>=0; j--) {
if (grid[i][j] < 0) {
output++;
} else {
break;
}
}
}
return output;
}
}
class Solution {
public int countNegatives(int[][] grid) {
int row = grid.length - 1, col = 0, res = 0;
while (row >= 0 && col < grid[0].length) {
if (grid[row][col] < 0) {
res += grid[0].length - col;
row--;
} else
col++;
}
return res;
}
}
class Solution {
public int countNegatives(int[][] grid) {
int m=grid.length,n=grid[0].length;
int num=0,right=n,left=0;
for(int i=0;i<m;i++){
// right=left;有没有这句都行,因为上一次循环结束时这句必然成立。
left=0;
while(left<right){
int middle=(left+right)/2;
if(grid[i][middle]>=0){
left=middle+1;
}else{
right=middle;
}
}
num+=(n-left);
}
return num;
}
}
你知道的越多,你不知道的越多。
有道无术,术尚可求,有术无道,止于术。
如有其它问题,欢迎大家留言,我们一起讨论,一起学习,一起进步