1.

 package algorithms.analysis14;

 import algorithms.util.In;
import algorithms.util.StdOut; /******************************************************************************
* Compilation: javac TwoSum.java
* Execution: java TwoSum input.txt
* Dependencies: StdOut.java In.java Stopwatch.java
* Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt
* http://algs4.cs.princeton.edu/14analysis/2Kints.txt
* http://algs4.cs.princeton.edu/14analysis/4Kints.txt
* http://algs4.cs.princeton.edu/14analysis/8Kints.txt
* http://algs4.cs.princeton.edu/14analysis/16Kints.txt
* http://algs4.cs.princeton.edu/14analysis/32Kints.txt
* http://algs4.cs.princeton.edu/14analysis/1Mints.txt
*
* A program with N^2 running time. Read in N integers
* and counts the number of pairs that sum to exactly 0.
*
*
* Limitations
* -----------
* - we ignore integer overflow
*
*
* % java TwoSum 2Kints.txt
* 2
*
* % java TwoSum 1Kints.txt
* 1
*
* % java TwoSum 2Kints.txt
* 2
*
* % java TwoSum 4Kints.txt
* 3
*
* % java TwoSum 8Kints.txt
* 19
*
* % java TwoSum 16Kints.txt
* 66
*
* % java TwoSum 32Kints.txt
* 273
*
******************************************************************************/ public class TwoSum { // print distinct pairs (i, j) such that a[i] + a[j] = 0
public static void printAll(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
if (a[i] + a[j] == 0) {
StdOut.println(a[i] + " " + a[j]);
}
}
}
} // return number of distinct triples (i, j) such that a[i] + a[j] = 0
public static int count(int[] a) {
int N = a.length;
int cnt = 0;
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
if (a[i] + a[j] == 0) {
cnt++;
}
}
}
return cnt;
} public static void main(String[] args) {
In in = new In(args[0]);
int[] a = in.readAllInts();
Stopwatch timer = new Stopwatch();
int cnt = count(a);
StdOut.println("elapsed time = " + timer.elapsedTime());
StdOut.println(cnt);
}
}

The answer to this question is that we have discussed and used two classic algorithms,
mergesort and binary search, have introduced the facts that the mergesort is linearith-
mic and binary search is logarithmic.

2.

 package algorithms.analysis14;

 /******************************************************************************
* Compilation: javac TwoSumFast.java
* Execution: java TwoSumFast input.txt
* Dependencies: In.java Stopwatch.java
* Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt
* http://algs4.cs.princeton.edu/14analysis/2Kints.txt
* http://algs4.cs.princeton.edu/14analysis/4Kints.txt
* http://algs4.cs.princeton.edu/14analysis/8Kints.txt
* http://algs4.cs.princeton.edu/14analysis/16Kints.txt
* http://algs4.cs.princeton.edu/14analysis/32Kints.txt
* http://algs4.cs.princeton.edu/14analysis/1Mints.txt
*
* A program with N log N running time. Read in N integers
* and counts the number of pairs that sum to exactly 0.
*
* Limitations
* -----------
* - we ignore integer overflow
*
*
* % java TwoSumFast 2Kints.txt
* 2
*
* % java TwoSumFast 1Kints.txt
* 1
*
* % java TwoSumFast 2Kints.txt
* 2
*
* % java TwoSumFast 4Kints.txt
* 3
*
* % java TwoSumFast 8Kints.txt
* 19
*
* % java TwoSumFast 16Kints.txt
* 66
*
* % java TwoSumFast 32Kints.txt
* 273
*
******************************************************************************/ import java.util.Arrays; import algorithms.util.In;
import algorithms.util.StdOut; public class TwoSumFast { // print distinct pairs (i, j) such that a[i] + a[j] = 0
public static void printAll(int[] a) {
int N = a.length;
Arrays.sort(a);
for (int i = 0; i < N; i++) {
int j = Arrays.binarySearch(a, -a[i]);
if (j > i) StdOut.println(a[i] + " " + a[j]);
}
} // return number of distinct pairs (i, j) such that a[i] + a[j] = 0
public static int count(int[] a) {
int N = a.length;
Arrays.sort(a);
int cnt = 0;
for (int i = 0; i < N; i++) {
int j = Arrays.binarySearch(a, -a[i]);
if (j > i) cnt++;
}
return cnt;
} public static void main(String[] args) {
In in = new In(args[0]);
int[] a = in.readAllInts();
int cnt = count(a);
StdOut.println(cnt);
}
}

  

3.

 package algorithms.analysis14;

 import algorithms.util.In;
import algorithms.util.StdOut; /******************************************************************************
* Compilation: javac ThreeSum.java
* Execution: java ThreeSum input.txt
* Dependencies: In.java StdOut.java Stopwatch.java
* Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt
* http://algs4.cs.princeton.edu/14analysis/2Kints.txt
* http://algs4.cs.princeton.edu/14analysis/4Kints.txt
* http://algs4.cs.princeton.edu/14analysis/8Kints.txt
* http://algs4.cs.princeton.edu/14analysis/16Kints.txt
* http://algs4.cs.princeton.edu/14analysis/32Kints.txt
* http://algs4.cs.princeton.edu/14analysis/1Mints.txt
*
* A program with cubic running time. Read in N integers
* and counts the number of triples that sum to exactly 0
* (ignoring integer overflow).
*
* % java ThreeSum 1Kints.txt
* 70
*
* % java ThreeSum 2Kints.txt
* 528
*
* % java ThreeSum 4Kints.txt
* 4039
*
******************************************************************************/ /**
* The <tt>ThreeSum</tt> class provides static methods for counting
* and printing the number of triples in an array of integers that sum to 0
* (ignoring integer overflow).
* <p>
* This implementation uses a triply nested loop and takes proportional to N^3,
* where N is the number of integers.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/14analysis">Section 1.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class ThreeSum { // Do not instantiate.
private ThreeSum() { } /**
* Prints to standard output the (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0.
* @param a the array of integers
*/
public static void printAll(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
for (int k = j+1; k < N; k++) {
if (a[i] + a[j] + a[k] == 0) {
StdOut.println(a[i] + " " + a[j] + " " + a[k]);
}
}
}
}
} /**
* Returns the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0.
* @param a the array of integers
* @return the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0
*/
public static int count(int[] a) {
int N = a.length;
int cnt = 0;
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
for (int k = j+1; k < N; k++) {
if (a[i] + a[j] + a[k] == 0) {
cnt++;
}
}
}
}
return cnt;
} /**
* Reads in a sequence of integers from a file, specified as a command-line argument;
* counts the number of triples sum to exactly zero; prints out the time to perform
* the computation.
*/
public static void main(String[] args) {
In in = new In(args[0]);
int[] a = in.readAllInts(); Stopwatch timer = new Stopwatch();
int cnt = count(a);
StdOut.println("elapsed time = " + timer.elapsedTime());
StdOut.println(cnt);
}
}

4.

 package algorithms.analysis14;

 /******************************************************************************
* Compilation: javac ThreeSumFast.java
* Execution: java ThreeSumFast input.txt
* Dependencies: StdOut.java In.java Stopwatch.java
* Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt
* http://algs4.cs.princeton.edu/14analysis/2Kints.txt
* http://algs4.cs.princeton.edu/14analysis/4Kints.txt
* http://algs4.cs.princeton.edu/14analysis/8Kints.txt
* http://algs4.cs.princeton.edu/14analysis/16Kints.txt
* http://algs4.cs.princeton.edu/14analysis/32Kints.txt
* http://algs4.cs.princeton.edu/14analysis/1Mints.txt
*
* A program with N^2 log N running time. Read in N integers
* and counts the number of triples that sum to exactly 0.
*
* Limitations
* -----------
* - we ignore integer overflow
* - doesn't handle case when input has duplicates
*
*
* % java ThreeSumFast 1Kints.txt
* 70
*
* % java ThreeSumFast 2Kints.txt
* 528
*
* % java ThreeSumFast 4Kints.txt
* 4039
*
* % java ThreeSumFast 8Kints.txt
* 32074
*
* % java ThreeSumFast 16Kints.txt
* 255181
*
* % java ThreeSumFast 32Kints.txt
* 2052358
*
******************************************************************************/ import java.util.Arrays; import algorithms.util.In;
import algorithms.util.StdOut; /**
* The <tt>ThreeSumFast</tt> class provides static methods for counting
* and printing the number of triples in an array of distinct integers that
* sum to 0 (ignoring integer overflow).
* <p>
* This implementation uses sorting and binary search and takes time
* proportional to N^2 log N, where N is the number of integers.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/14analysis">Section 1.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class ThreeSumFast { // Do not instantiate.
private ThreeSumFast() { } // returns true if the sorted array a[] contains any duplicated integers
private static boolean containsDuplicates(int[] a) {
for (int i = 1; i < a.length; i++)
if (a[i] == a[i-1]) return true;
return false;
} /**
* Prints to standard output the (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0.
* @param a the array of integers
* @throws IllegalArgumentException if the array contains duplicate integers
*/
public static void printAll(int[] a) {
int N = a.length;
Arrays.sort(a);
if (containsDuplicates(a)) throw new IllegalArgumentException("array contains duplicate integers");
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
int k = Arrays.binarySearch(a, -(a[i] + a[j]));
if (k > j) StdOut.println(a[i] + " " + a[j] + " " + a[k]);
}
}
} /**
* Returns the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0.
* @param a the array of integers
* @return the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0
*/
public static int count(int[] a) {
int N = a.length;
Arrays.sort(a);
if (containsDuplicates(a)) throw new IllegalArgumentException("array contains duplicate integers");
int cnt = 0;
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
int k = Arrays.binarySearch(a, -(a[i] + a[j]));
if (k > j) cnt++;
}
}
return cnt;
} /**
* Reads in a sequence of distinct integers from a file, specified as a command-line argument;
* counts the number of triples sum to exactly zero; prints out the time to perform
* the computation.
*/
public static void main(String[] args) {
In in = new In(args[0]);
int[] a = in.readAllInts();
int cnt = count(a);
StdOut.println(cnt);
}
}

算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-002如何改进算法的更多相关文章

  1. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-005计测试算法

    1. package algorithms.analysis14; import algorithms.util.StdOut; import algorithms.util.StdRandom; / ...

  2. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-007按位置,找出数组相关最大值

    Given an array a[] of N real numbers, design a linear-time algorithm to find the maximum value of a[ ...

  3. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-006BitonicMax

    package algorithms.analysis14; import algorithms.util.StdOut; import algorithms.util.StdRandom; /*** ...

  4. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-004计算内存

    1. 2. 3.字符串

  5. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-003定理

    1. 2. 3. 4. 5. 6.

  6. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-001分析步骤

    For many programs, developing a mathematical model of running timereduces to the following steps:■De ...

  7. 算法Sedgewick第四版-第1章基础-001递归

    一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归, ...

  8. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-001选择排序法(Selection sort)

    一.介绍 1.算法的时间和空间间复杂度 2.特点 Running time is insensitive to input. The process of finding the smallest i ...

  9. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)

    一. 1. 2. 3. 二.代码 package algorithms.mergesort22; import algorithms.util.StdIn; import algorithms.uti ...

随机推荐

  1. gulp插件之-----转化es6代码到es5 取消严格模式 remove "use strict" directive

    Installation npm install babel-plugin-transform-remove-strict-mode && yarn add babel-plugin- ...

  2. ContextMenuStrip 动态添加多级子菜单

    1.首先要实例化几个ToolStripItem(要为某一父菜单添加几个子菜单就实例化几个):方法如下: /*添加子菜单*/ ToolStripItem ts_1 = new ToolStripMenu ...

  3. 魔法效果——dijkstra+堆(邻接表存储)

    dijkstra本身每次要for一遍,才能找出最小的节点,但用了堆之后,直接取出堆首就可以了. 但要注意的一点是,c++自带的stl里的priority_queue本身是先入大出的,而我们要求的是最小 ...

  4. java多线程并发去调用一个类的静态方法安全性探讨

    java多线程并发去调用一个类的静态方法安全性探讨 转自:http://blog.csdn.net/weibin_6388/article/details/50750035   这篇文章主要讲多线程对 ...

  5. HDFS超租约异常总结(org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException)

    HDFS超租约异常总结(org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException) 转载 2014年02月22日 14:40:58 96 ...

  6. Why getting this error “django.db.utils.OperationalError: (1050, ”Table 'someTable' already exists“)”

    0down votefavorite   I am getting error like django.db.utils.OperationalError: (1050, "Table 's ...

  7. CF 36E Two Paths——欧拉路

    题目:http://codeforces.com/contest/36/problem/E 找出两条欧拉路覆盖无向图. 套上欧拉路模板.用过的边要记录. 注意 一个连通块.4个奇度数点 的情况是在两个 ...

  8. CentOS7网卡设置为桥接模式静态IP配置方法详解

    备份网络文件 [root@localhost network-scripts]# cd /etc/sysconfig/network-scripts/ [root@localhost network- ...

  9. 机器学习:使用scikit-learn库中的网格搜索调参

    一.scikit-learn库中的网格搜索调参 1)网格搜索的目的: 找到最佳分类器及其参数: 2)网格搜索的步骤: 得到原始数据 切分原始数据 创建/调用机器学习算法对象 调用并实例化scikit- ...

  10. PV 和 UV IP

    PV(page view),即页面浏览量,或点击量;通常是衡量一个网络新闻频道或网站甚至一条网络新闻的主要指标. 高手对pv的解释是,一个访问者在24小时(0点到24点)内到底看了你网站几个页面.这里 ...