【算法】程序猿不写代码是不对的77
来源:互联网 发布:ubuntu默认账号密码 编辑:程序博客网 时间:2024/06/07 03:56
package com.kingdz.algorithm.time201707;import java.util.ArrayList;import java.util.Collections;import java.util.List;/** * <pre> * 多少个三角形 * * http://judgecode.com/problems/1009 * * How many triangle triples * A non-empty zero-indexed array A consisting of N integers is given. * Please calculate how many triangle triple indices in it. * A triangle triple index is a triple of integers 0 <= P < Q < R < N such that * A[P] + A[Q] > A[R] * A[p] + A[R] > A[Q] * A[Q] + A[R] > A[P] * * Input:A list of N non-negative integers less than 1000000. N is no larger than 2000. * </pre> * * @author kingdz * */public class Algo06 {public static void main(String[] args) {String input = "1 2 3 4 5 6 7 8";int number = calculate(input);System.out.println("triangle triples number:" + number);}private static int calculate(String input) {String[] array = input.split(" ");List<Integer> list = new ArrayList<Integer>();for (String str : array) {list.add(Integer.parseInt(str));}// 这个数列从小到大排序Collections.sort(list);int count = 0;int i = 0;while (true) {i++;// 求出二进制字符串String str = Integer.toBinaryString(i);if (str.length() > list.size()) {// 如果字符串长度超长了,则说明遍历了所有的组合break;}// 求出字符串中1的个数int length = str.replace("0", "").length();// 如果有3个1则说明是选择了三条边if (length == 3) {// 将这个字符串根据所需要的长度左补0补全字符串StringBuilder strb = new StringBuilder();for (int j = 0; j < list.size() - str.length(); j++) {strb.append("0");}strb.append(str);str = strb.toString();// 标记位,为了给abc赋值int mark = 0;// 定义三个变量保存三角形的三条边int a = 0;int b = 0;int c = 0;for (int j = 0; j < str.length(); j++) {if (str.charAt(j) == '1') {if (mark == 0) {a = list.get(j);mark = 1;} else if (mark == 1) {b = list.get(j);mark = 2;} else if (mark == 2) {c = list.get(j);break;}}}if (a + b > c) {count++;}}}return count;}}
阅读全文
0 0
- 【算法】程序猿不写代码是不对的77
- 【算法】程序猿不写代码是不对的1
- 【算法】程序猿不写代码是不对的2
- 【算法】程序猿不写代码是不对的3
- 【算法】程序猿不写代码是不对的4
- 【算法】程序猿不写代码是不对的5
- 【算法】程序猿不写代码是不对的6
- 【算法】程序猿不写代码是不对的7
- 【算法】程序猿不写代码是不对的8
- 【算法】程序猿不写代码是不对的9
- 【算法】程序猿不写代码是不对的10
- 【算法】程序猿不写代码是不对的11
- 【算法】程序猿不写代码是不对的12
- 【算法】程序猿不写代码是不对的13
- 【算法】程序猿不写代码是不对的14
- 【算法】程序猿不写代码是不对的15
- 【算法】程序猿不写代码是不对的16
- 【算法】程序猿不写代码是不对的17
- Vue1.x
- 【小狂系列】跟着小狂玩ESP32之编译环境搭建篇
- 二分搜索
- 遍历List集合的三种方法
- pythonsql操作2
- 【算法】程序猿不写代码是不对的77
- java clone方法使用详解
- Thread Dumps基本范例
- 新闻动态
- 51Nod-最大子段和(动态规划)
- visual studio2013 中配置 opencv3.0
- vmware虚拟机上ubuntu 10.04不能连上外网解决办法----本人备注
- python学习资料
- Android文件存储全攻略