找出连续最长的数字串_数组中出现次数超过一半的数字_计算糖果

字符串中找出连续最长的数字串

字符串中找出连续最长的数字串

image-20220430090113079

import java.util.*;
public class Main{
    public static String findLongNumberStr(String str){
        String strResult = new String();
        String tmp = new String();
        for(int i = 0;i < str.length();i++){
            char ch = str.charAt(i);
            if(ch>='0'&&ch<='9'){//该位置是数字!!
                tmp +=(""+ch); //拼接!
            }else{ 
                //不连续!
                if(strResult.length()<tmp.length()){
                       strResult = tmp;//更新结果!
                }
                tmp = new String();
            }
        }
        //如果最长数字序列在最后,需要单独进行处理!!!
        if(strResult.length()<tmp.length()){
                       strResult = tmp;//更新结果!
          }
        return strResult;
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        String result = findLongNumberStr(str);
        System.out.println(result);
    }
}

数组中出现次数超过一半的数字

题目链接

image-20220430091529600

import java.util.Arrays;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        if(array==null||array.length==0){
            return -1;
        }
        //先将数组排序!!!
        //排序后,中间的数就是出现次数超过了长度一半的数!
        Arrays.sort(array);
        int len = array.length;
        int midNumber = array[len/2];
      return midNumber;
    }
}

计算糖果

计算糖果

image-20220430102340704

// 要求ABC都为整数
// 注意多了一个约束条件,即四个式子解3个未知数,所以还要确定满不满足A+B==n3
import java.util.Scanner;
public class Main {    
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n1 = in.nextInt();
        int n2 = in.nextInt();
        int n3 = in.nextInt();
        int n4 = in.nextInt();
        int A = (n1+n3)/2;
        int B = (n2+n4)/2;
        int C = B-n2;
        //这里的取余操作,保证用例满足条件!
        // 例如: 0 -1 3 5 NO!
        // A+B == n3 保证解是正确符号题意的!
        // 11 -7 0 error 
        if((n1+n3)%2==0&&(n2+n4)%2==0&&(A+B==n3)){
            System.out.println(A+" "+B+" "+C);
        }else{
            System.out.println("No");
        }
    }
}
//常规方法!
import java.util.Scanner;
public class Main {    
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n1 = in.nextInt();// A - B
        int n2 = in.nextInt();// B - C 
        int n3 = in.nextInt();// A + B 
        int n4 = in.nextInt();// B + C
        int A = (n1+n3)/2;// A
        int B1 = (n2+n4)/2;// B1
        int B2 = (n3-n1)/2;// B2
        int C =  (n4-n2)/2;// C 
        if(B1==B2){//B1 == B2 说明解是正确的!
            System.out.println(A+" "+B1+" "+C);
        }else{
            System.out.println("No");
        }
    }
}
#算法题#
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务