在一个不重复的数组中,统计有多少组两个元素相加得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. POJ 1953 World Cup Noise(递推)

    https://vjudge.net/problem/POJ-1953 题意:输入一个n,这n位数只由0和1组成,并且不能两个1相邻.计算共有多少种排列方法. 思路:递推题. 首先a[1]=2,a[2 ...

  2. Thunder团队Alpha周贡献分规则及贡献分分配结果

    小组名称:Thunder 项目名称:爱阅app 组长:王航 成员:李传康.代秋彤.邹双黛.苗威.宋雨.胡佑蓉.杨梓瑞 Alpha周贡献分分配结果

  3. RabbitMQ入门_15_访问控制

    参考资料:https://www.rabbitmq.com/access-control.html A. 核心概念 Virtual Host:虚拟主机为 RabbitMQ 中的资源提供了逻辑分组与隔离 ...

  4. 解决RDP连接不上

    1,开始->运行 regedit 删除注册表项目:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft, 删除MSLicensing.2,开始--运行 mstsc /v:( ...

  5. HDU 2569 彼岸

    彼岸 思路:动态规划.因为不能有连续三个不同的颜色,所以只要看最后三个就可以了. 设dp[n]为长度为n到达彼岸的方案数. ①当第n-2个颜色和第n-1个颜色相同时,第n个位置可以取任意一种颜色,dp ...

  6. Lua面向对象 --- 继承

    工程结构: BasePlayer.lua: BasePlayer = {} BasePlayer.root = "BasePlayer" function BasePlayer:S ...

  7. Sasha and a Very Easy Test CodeForces - 1109E (数学,线段树)

    大意: 给定n元素序列, q个操作: (1)区间乘 (2)单点除(保证整除) (3)区间求和对m取模 要求回答所有操作(3)的结果 主要是除法难办, 假设单点除$x$, $x$中与$m$互素的素因子可 ...

  8. array_unshift

    <!DOCTYPE html> <html> <body> <?php $a=array(0=>"red",1=>" ...

  9. 新项目中使用的linux命令

    要通过跳板机进入内网之后,访问内网域名 mysql -h xxxxxxx -u u_caojiangjiang -p -P 3306 上传文件: scp -r /Users/qudian/Deskto ...

  10. 『科学计算』科学绘图库matplotlib练习

    思想:万物皆对象 作业 第一题: import numpy as np import matplotlib.pyplot as plt x = [1, 2, 3, 1] y = [1, 3, 0, 1 ...