基础算法(贪心 合并 位运算)


最长连续不重复子序列

public class 最长连续不重复子序列 {
    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);
        int N = sc.nextInt();
        int[] str1 = new int[100010];
        int[] str2 = new int[100010];
        for (int i=0;i<N;i++){
            str1[i]=sc.nextInt();
        }
        int res = 0;
        for(int i=0,j=0;i<N;i++){
            str2[str1[i]]+=1;
            while(str2[str1[i]]>1){
                str2[str1[j]]--;
                j++;
            }
            res = Math.max(res,i-j+1);
        }
        System.out.println(res);
    }
}

区间合并

public class 区间合并 {
    public static void merge(int[][] str){
        if(str.length==0){
            System.out.println(0);
        }
        int st = str[0][0];
        int ed = str[0][1];
        int n = 1;
        for(int i=1;i<str.length;i++){
            if(ed<str[i][0]){
                st = str[i][0];
                ed = str[i][1];
                n++;
            }else{
                ed = Math.max(ed,str[i][1]);
            }
        }
        System.out.println(n);
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] str = new int[n][2];
        for(int i=0;i<n;i++){
            str[i][0]=sc.nextInt();
            str[i][1]=sc.nextInt();
        }
        Arrays.sort(str, new Comparator<int[]>() {    // 匿名内部类
            @Override
            public int compare(int[] e1, int[] e2) {
                // 如果第一列元素相等,则比较第二列元素
                if (e1[0]==e2[0]) return e1[1]-e2[1];   // e1[1]-e2[1]表示对于第二列元素进行升序排序
                return e1[0]-e2[0];                     // e1[0]-e2[0]表示对于第一列元素进行升序排序
            }
        });
        merge(str);
    }
}

位运算

public class 位运算 {
    public static void main(String[] args) {
        int n = 100;
        for (int k=7;k>=0;k--) System.out.print(n >> k & 1);
    }
}

求二进制中一的个数

public class 求二进制中一的个数 {
    public static int lowbit(int x){
        return x & -x;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int res = 0;
        while (x!=0) {
            x-=lowbit(x);
            res++;
        }
        System.out.println(res);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨宸杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值