这个拖了比较久,春节放假终于补回来了。
1317. 将整数转换为两个无零整数的和
class Solution {
public int[] getNoZeroIntegers(int n) {
int [] res = new int[2];
//int number =(int) (Math.random()*(n-1))+1;
int i=1;
for(;i<n;i++){
if(!String.valueOf(i).contains("0")){
if(!String.valueOf(n-i).contains("0")){
break;
}
}
}
res[0] = i;
res[1] = n - i;
return res ;
}
}
1318. 或运算的最小翻转次数
class Solution {
public int minFlips(int a, int b, int c) {
int count = 0;
while(a>0 || b>0 || c>0){
int tempA = a&1;
int tempB = b&1;
int tempC = c&1;
if((tempA|tempB) != tempC){
int temp = tempA|tempB;
if(temp == 0 && tempC==1){
count+=1;
}else if(tempC==0){
count = count + (tempA==tempB?2:1);
}
}
a = a>>1;
b = b>>1;
c = c>>1;
}
return count;
}
}
1319. 连通网络的操作次数
借鉴了别人的做法
考察了并查集的解法
解题思路
连接n个点至少需要n-1 根线,如果不够n-1直接返回-1
初始化每个点的头结点是自己
遍历数组,给每一组两个数连线
如果两个点的头结点一致,则说明已经连在一起了,否则选择一个点作为共同的头结点
从0开始查找每个点的头结点是不是自己,如果是自己则说明是一个独立的圈
如果全部连在一起则count == 1,否则超过1个圈就是需要连接n-1根线连接起来
class Solution {
int [] father ;
public int makeConnected(int n, int[][] connections) {
int length = connections.length;
int count = 0;
if(length<n-1){
return -1;
}
father = new int[n];
for(int i=0;i<n;i++){
father[i] = i;
}
for(int j=0;j<length;j++){
union(connections[j][0], connections[j][1]);
}
for(int k=0;k<n;k++){
if(findFather(k)==k){
count++;
}
}
return count-1;
}
public void union(int a,int b){
int i = findFather(a);
int j = findFather(b);
if(i!=j){
father[i] = j;
}
}
public int findFather(int i){
if(father[i]==i){
return i;
}else{
int res = findFather(father[i]);
return res;
}
}
}