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

勤奋不是嘴上说说而已,而是实际的行动,在勤奋的苦度中持之以恒,永不退却。业精于勤,荒于嬉;行成于思,毁于随。在人生的仕途上,我们毫不迟疑地选择勤奋,她是几乎于世界上一切成就的催产婆。只要我们拥着勤奋去思考,拥着勤奋的手去耕耘,用抱勤奋的心去对待工作,浪迹红尘而坚韧不拔,那么,我们的生命就会绽放火花,让人生的时光更加的闪亮而精彩。

导读:本篇文章讲解 基础算法(贪心 合并 位运算),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文


最长连续不重复子序列

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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/141567.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!