在一个不重复的数组中,统计有多少组两个元素相加得0。

这里使用三种方式实现,并统计他们各自花费的时间:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Random; public class TwoSum {
private static int N = 100000;
private static int[] a = new int[N];
private static Random random = new Random();
private static HashMap<Integer, Boolean> m = new HashMap<Integer, Boolean>(); private int binarySearch(int[] a, int num) {
int low = 0, mid = 0, high = a.length - 1;
while (low <= high) {
mid = low + (high - low) / 2;
if (a[mid] > num) {
high = mid - 1;
} else if (a[mid] < num) {
low = mid + 1;
} else {
return mid;
}
} return -1;
} public int solution1() {
int count = 0;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
if (a[i] + a[j] == 0) {
count++;
}
}
}
return count;
} public int solution2() {
int count = 0;
Arrays.sort(a);
for (int i = 0; i < N; i++) {
if (binarySearch(a, -a[i]) > i) {
count++;
}
}
return count;
} public int solution3() {
int count = 0;
for (int i = 0; i < N; i++) {
if (m.containsKey(-a[i])) {
count++;
}
}
return count / 2;
} public static int uniform(int N) {
if (N <= 0) throw new IllegalArgumentException("Parameter N must be positive");
return random.nextInt(N);
} public int uniform(int a, int b) {
if (b <= a) throw new IllegalArgumentException("Invalid range");
if ((long) b - a >= Integer.MAX_VALUE) throw new IllegalArgumentException("Invalid range");
return a + uniform(b - a);
} public static void main(String[] args) {
TwoSum ts = new TwoSum();
int count = 0;
int rand = 0;
int i = 0;
boolean flag = true; while (i < a.length) {
rand = ts.uniform(-10000000, 10000000);
flag = true;
for (int j = 0; j < a.length; j++) {
if (a[j] == rand) {
flag = false;
break;
}
}
if (flag) {
a[i] = rand;
i++;
//System.out.println(rand + " " + flag);
}
} for (int j = 0; j < N; j++) {
m.put(a[j], true);
} Stopwatch timer1 = new Stopwatch();
count = ts.solution1();
double time = timer1.elapsedTime();
System.out.println("count1: " + count + " cost1: " + time); count = 0;
time = 0;
Stopwatch timer2 = new Stopwatch();
count = ts.solution2();
time = timer2.elapsedTime();
System.out.println("count2: " + count + " cost2: " + time); count = 0;
time = 0;
Stopwatch timer3 = new Stopwatch();
count = ts.solution3();
time = timer3.elapsedTime();
System.out.println("count3: " + count + " cost3: " + time);
}
}

solution1:直接使用一个两层for循环,所以最终的时间复杂度为O(N^2);

solution2:先将数组排序,然后通过二分查找来搜索数组中每个元素的相反数,此时的时间复杂度为O(N*log(N));

solution3:和方法一类似,只不过是通过哈希表中查找元素的复杂度为O(1)来优化搜索时间,此时时间复杂度为O(N);

当N=1000时

count1: 0 cost1: 0.004
count2: 0 cost2: 0.002
count3: 0 cost3: 0.001 当N=10000时 count1: 5 cost1: 0.026
count2: 5 cost2: 0.009
count3: 5 cost3: 0.005 当N=100000时 count1: 238 cost1: 2.296
count2: 238 cost2: 0.077
count3: 238 cost3: 0.012

这里因为产生不重复的随机数使用的是最简单的两层循环,所以当数组的length太大时,比如1000000时,在产生随机数的过程中会消耗很长时间,这一部分可以使用其他更优的方法实现。

TwoSum:两数相加得0的更多相关文章

  1. LeetCode 0、《两数相加》

    一.给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表. 你可以假设除了数字 0 之外,这两个数字都不会以零开头. 示例: 输入:(2 ...

  2. ✡ leetcode 167. Two Sum II - Input array is sorted 求两数相加等于一个数的位置 --------- java

    Given an array of integers that is already sorted in ascending order, find two numbers such that the ...

  3. 两数之和,两数相加(leetcode)

    我们都知道算法是程序员成长重要的一环,怎么才能提高算法呢, 出来在网上看视频之外,动手练习是非常重要的.leetcode 就是一个非常好的锻炼平台. 1. 两数之和,在 leetcode 里面是属于 ...

  4. leetCode:twoSum 两数之和 【JAVA实现】

    LeetCode 两数之和 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标. 您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素. 更多文章查看个人博客 个人博客地址:t ...

  5. [CareerCup] 18.1 Add Two Numbers 两数相加

    18.1 Write a function that adds two numbers. You should not use + or any arithmetic operators. 这道题让我 ...

  6. [Swift]LeetCode2. 两数相加 | Add Two Numbers

    You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...

  7. [Swift]LeetCode445. 两数相加 II | Add Two Numbers II

    You are given two non-empty linked lists representing two non-negative integers. The most significan ...

  8. day2——两数相加

    // 小白一名,0算法基础,艰难尝试算法题中,若您发现本文中错误, 或有其他见解,往不吝赐教,感激不尽,拜谢. 领扣 第2题 今日算法题干//给定两个非空链表来表示两个非负整数.位数按照逆序方式存储, ...

  9. leetcode 刷题(2)--- 两数相加

    给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表. 你可以假设除了数字 0 之外,这两个数字都不会以零开头. 示例: 输入:(2 -& ...

随机推荐

  1. hibernate与mybatis的区别和应用场景

    mybatis 与 hibernate 的区别和应用场景(转) 1    Hibernate : 标准的ORM(对象关系映射) 框架: 不要用写sql, sql 自动语句生成: 使用Hibernate ...

  2. Python的collections模块中的OrderedDict有序字典

    如同这个数据结构的名称所说的那样,它记录了每个键值对添加的顺序. ? 1 2 3 4 5 6 d = OrderedDict() d['a'] = 1 d['b'] = 10 d['c'] = 8 f ...

  3. python 判断一个数字是否为4的幂

    def is_Power_of_four(n): while n and not (n & 0b11): n >>= ) print(is_Power_of_four()) pri ...

  4. 《F4+2团队项目系统设计改进》

    项目软件系统设计改进 1引言 1.1编写目的 本阶段完成系统的大致设计并明确系统的数据结构与软件结构.本概要设计说明书的目的就是进一步细化软件设计阶段得出的软件概貌,把它加工成在程序细节上非常接近与源 ...

  5. Linux 之 ./configure --prefix 命令

    参考 http://blog.sina.com.cn/s/blog_406127500101dsmy.html 源码的安装一般由3个步骤组成:配置(configure).编译(make).安装(mak ...

  6. java.lang.NoSuchMethodError问题处理

    出现这个问题一般是jar包冲突了,我找了很久没找到是哪个jar冲突了.最后用下面的这段代码,找到是哪个jar冲突了 /** * find jar file */ String LOCATION = & ...

  7. 机器学习 Matplotlib库入门

    2017-07-21 15:22:05 Matplotlib库是一个优秀的python的数据可视化的第三方类库,其中的pyplot支持了类似matlab的图像输出操作.matplotlib.pyplo ...

  8. [Java学习] Java instanceof 运算符

    多态性带来了一个问题,就是如何判断一个变量所实际引用的对象的类型 . C++使用runtime-type information(RTTI),Java 使用 instanceof 操作符. insta ...

  9. 测序中Q20 Q30 Q40

    你能给别人讲清楚这个概念吗? 二代测序中,每测一个碱基会给出一个相应的质量值,这个质量值是衡量测序准确度的.碱基的质量值13,错误率为5%,20的错误率为1%,30的错误率为0.1%.行业中Q20与Q ...

  10. Android之MVP模式实现登录和网络数据加载

    MVP简介 相信大家对 MVC 都是比较熟悉了:M-Model-模型.V-View-视图.C-Controller-控制器,MVP作为MVC的演化版本,也是作为用户界面(用户层)的实现模式,那么类似的 ...