TwoSum:两数相加得0
在一个不重复的数组中,统计有多少组两个元素相加得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的更多相关文章
- LeetCode 0、《两数相加》
一.给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表. 你可以假设除了数字 0 之外,这两个数字都不会以零开头. 示例: 输入:(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 ...
- 两数之和,两数相加(leetcode)
我们都知道算法是程序员成长重要的一环,怎么才能提高算法呢, 出来在网上看视频之外,动手练习是非常重要的.leetcode 就是一个非常好的锻炼平台. 1. 两数之和,在 leetcode 里面是属于 ...
- leetCode:twoSum 两数之和 【JAVA实现】
LeetCode 两数之和 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标. 您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素. 更多文章查看个人博客 个人博客地址:t ...
- [CareerCup] 18.1 Add Two Numbers 两数相加
18.1 Write a function that adds two numbers. You should not use + or any arithmetic operators. 这道题让我 ...
- [Swift]LeetCode2. 两数相加 | Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...
- [Swift]LeetCode445. 两数相加 II | Add Two Numbers II
You are given two non-empty linked lists representing two non-negative integers. The most significan ...
- day2——两数相加
// 小白一名,0算法基础,艰难尝试算法题中,若您发现本文中错误, 或有其他见解,往不吝赐教,感激不尽,拜谢. 领扣 第2题 今日算法题干//给定两个非空链表来表示两个非负整数.位数按照逆序方式存储, ...
- leetcode 刷题(2)--- 两数相加
给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表. 你可以假设除了数字 0 之外,这两个数字都不会以零开头. 示例: 输入:(2 -& ...
随机推荐
- 从零开始的四轴飞行器-开篇flag
在这里立下flag,我要理解学会四轴飞行器的控制方法.
- HDU 3466 Proud Merchants(0-1背包)
http://acm.hdu.edu.cn/showproblem.php?pid=3466 题意: 最近,iSea去了一个古老的国家.在这么长的时间里,它是世界上最富有和最强大的王国.结果,这个国家 ...
- java 使用正则判断是不是一个数字
public class Numeric { public static void main(String[] args) { String string = "-1234.15" ...
- Jmeter自动化测试 数据驱动测试,将数据存入csv文件中来调用,或将数据存在DB中进行调用
1. 将测试的用例名称,测试请求方式,测试链接,预置数据,断言等都放到excel中,然后转成csv格式,在用Jmeter带的csv数据配置文件导入 运行之前将线程组中配置,线程数设置为1,循环的次数设 ...
- Windows10中注册 regsvr32 xxx.ocx报错but the call to DIIRegisterServer failed with error code 0x80040200
网站中有读取居民身份证的机器,需要安装一些注册activeX控件然后进入指定目录下执行以下命令regsvr32 xxx.ocx报了个错: but the call to DIIRegisterServ ...
- 《剑指offer》第三_一题(找出数组中重复的数字,可改变数组)
// 面试题3(一):找出数组中重复的数字 // 题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内.数组中某些数字是重复的,但不知道有几个数字重复了, // 也不知道每个数字重复了几次.请 ...
- php新手第一次安装mongo
以下是我走位php新手第一次安装mongo模块的步骤: 1.首先从在网上选取适当版本的mongoDB扩展包下载; 2.解压扩展包,并且进入解压目录; tar -zxf mongo-1.4.1.tgz ...
- win10 WiFi 密码查询 命令
如果你笔记本有WiFi,正好你系统又是Win10 那么... netsh wlan show profile * key=clear
- 『科学计算』图像检测微型demo
这里是课上老师给出的一个示例程序,演示图像检测的过程,本来以为是传统的滑窗检测,但实际上引入了selectivesearch来选择候选窗,所以看思路应该是RCNN的范畴,蛮有意思的,由于老师的注释写的 ...
- MVC5 学习笔记 controller
主要参考书籍<ASP.NET MVC5 高级编程(第5版) > 作者:Jon Galloway等 1. MVC 表示 模型-视图-控制器.MVC是一种用于开发应用程序的模式,具备良好的架构 ...