算法练习(61): 计算数组中相等的整数对(1.4.8)

本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本人新建了一个微信群(算法交流),想要加入的,请添加我的微信号:zhujinhui207407 谢谢。另外,本人的个人博客 http://www.kyson.cn 也在不停的更新中,欢迎一起讨论

算法(第4版)

知识点

  • 成本模型

题目

1.4.8 编写一个程序,计算输入文件中相等的整数对的数量.如果你的第一个程序是平方级别的,请继续思考并以Array.sort()给出一个线性对数级别的解答


1.4.8 Write a program to determine the number pairs of values in an input file that are equal. If your first try is quadratic, think again and use Arrays.sort() to develop a linearithmic solution.

答案

public class TwoSame {
    public static int twoSame(long[] a){
        int cnt = 0;
        for (int i = 0; i < a.length; i++)
        {
            for (int j = i+1 ; j < a.length; j++) 
            {
                if (a[i] == a[j]) {
                    cnt++;
                }
            }
        }
        return cnt;
    }

    public static void main(String[] args) {
        String filePathString = System.getProperty("user.dir");
        String intFileString = filePathString
                + "/src/com/kyson/chapter1/section4/" + "1kints.txt";

        In in = new In(intFileString);
        long[] a = in.readAllLongs();
        
        System.out.println("相同的整数的数量为"+ twoSame(a));
    }
}

这个程序(的算法复杂度)是平方级别的,我们下面做个改动,变成线性级别的

public class TwoSameFast {
    public static int twoSameFast(long[] a){
        int cnt = 0;
        for (int i = 0; i < a.length - 1; i++) 
        {
            if (a[i] == a[i+1]) {
                cnt++;
            }
        }
        return cnt;
    }

    public static void main(String[] args) {
        String filePathString = System.getProperty("user.dir");
        String intFileString = filePathString
                + "/src/com/kyson/chapter1/section4/" + "1kints.txt";

        In in = new In(intFileString);
        long[] a = in.readAllLongs();
        Arrays.sort(a);
        
        System.out.println("相同的整数的数量为" + twoSameFast(a));
    }
}

代码索引

TwoSame.java
TwoSameFast.java

广告

我的首款个人开发的APP壁纸宝贝上线了,欢迎大家下载。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,270评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,359评论 19 139
  • 狭窄路边有个摊位 摆卖着各种小动物 画眉在梳理着羽毛 兔子则是一脸呆萌 只有一只黑色松鼠 在笼子里不停窜跳 那渴望...
    读书女子阅读 1,696评论 0 1
  • 标准库与泛型编程 内容提示:泛型编程(GP)与面向对象编程(OOP)的根本差异,模板的意义以及运用。 课程目标: ...
    鬼方纾秴阅读 2,920评论 0 0