和为s的两个数字
来源:互联网 发布:怎么查淘宝单号码查询 编辑:程序博客网 时间:2024/06/05 19:49
一:题目描述:
二:Code:
两种方法:
import java.util.Arrays;import org.junit.Test;public class totalArray { public void printResult(int a, int b) { System.out.println(a + "+" + b); } // 时间复杂度O(n^2) public void twoSum(int[] array, int s) { int len = array.length; for (int i = 0; i <= len - 1; i++) { for (int j = i + 1; j <= len - 1; j++) { if (array[i] + array[j] == s) { printResult(array[i], array[j]); break; } } } } //// 时间复杂度为线性 public void twoSum02(int[] array, int s) { int i = 0; int j = array.length - 1; while (i < j) { int sum = array[i] + array[j]; if (sum == s) { printResult(array[i], array[j]); i++; j--; } else if (sum > s) { j--; } else { i++; } } } // 给定的数组已经排好序了,所以用二分查找,时间复杂度为O( nlog(n) ) public void twoSum03(int[] array, int s) { int n = array.length; for (int i = 0; i < n - 1; i++) { int another = s - array[i]; if (Arrays.binarySearch(array, i + 1, n, another) >= i + 1) { printResult(array[i], another); } } } @Test public void testTwosum() { int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int s = 10; twoSum03(array, s); }}
0 0
- 和为S的两个数字
- 和为S的两个数字
- 找出和为S的两个数字
- 和为S的两个数字
- 【5】和为s的两个数字
- 和为S的两个数字
- 和为s的两个数字
- 和为s的两个数字
- 和为S的两个数字
- 和为S的两个数字
- 和为S的两个数字
- 和为s的两个数字
- 和为s的两个数字
- 牛客网 | 和为S的两个数字
- 和为s的两个数字
- 和为S的两个数字
- 和为S的两个数字
- 和为S的两个数字
- 好久不写东西的时候,再提笔有些困难。
- Codeforces Round #356 (Div. 1) D. Bear and Chase 暴力 ★ ★
- Andorid基础 Android系统层次框架结构
- 对象和类
- 1875-畅通工程再续
- 和为s的两个数字
- QMainWindow中添加layout的问题
- PF位的意义
- Java反射机制
- POJ 1742 Coins 混合三种背包问题
- Fragment 布局
- 手机互连(Mobile Connect)简介
- 安全卫士随记
- UOJ 150 [NOIP2015]运输计划