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 -& ...
随机推荐
- 2017年P4中国峰会北京站 会议小结
2017 P4 中国峰会 北京 本次会议依然侧重介绍P4,并highlight P4的benifit,大致分为以下几类: 1.学术界 - 未来网络的发展,为何提出P4技术? 未来网络和实体经济.其他学 ...
- Codeforces Beta Round #95 (Div. 2) D. Subway dfs+bfs
D. Subway A subway scheme, classic for all Berland cities is represented by a set of n stations conn ...
- re.sub
1.re.sub主要功能实现正则的替换. re.sub定义: sub(pattern, repl, string, count=0, flags=0) 意思为:对字符串string按照正则表达式pat ...
- 使用CMake在Linux下编译tinyxml静态库
环境:CentOS6.6+tinyxml_2_6_21.下载并解压tinyxml_2_6_2.zip unzip tinyxml_2_6_2.zip 2.在tinyxml文件夹里创建一个CMakeLi ...
- 新视觉影院yy6080.org视频的抓取
用fiddler 分析了一下, 从点连接 到 视频播放的过程 http://yy6080.org/v/103390 http://id.jiathis.com/id.php?u=http%3A%2F% ...
- 20170711xlVBA批量制图一例
Public Sub GatherDataPicker() Application.ScreenUpdating = False Application.DisplayAlerts = False A ...
- spoj The Next Palindrome
题意:比给出的数大的最小回文数. 先用前n/2长对称到后面,如果没变大,在中间加1,进位,再对称. //#pragma comment(linker,"/STACK:1024000000,1 ...
- bzoj4589: Hard Nim fwt
题意:求n个m以内的素数亦或起来为0的方案数 题解:fwt板子题,先预处理素数,把m以内素数加一遍(下标),然后fwt之后快速幂即可,在ifwt之后a[0]就是答案了 /*************** ...
- 总结: MySQL(基础,字段约束,索引,外键,存储过程,事务)操作语法
1. 显示数据库列表 show databases; # 查看当前所有数据库 show databases \G #以行的方式显示 2. 在命令行中,执行sql语句 mysql -e 'show ...
- Hackintosh Power Management
Also, be aware that hibernation (suspend to disk or S4 sleep) is not supported on hackintosh. You sh ...