首页 > 代码库 > GetNumber的实现(Python & Java & Golang)

GetNumber的实现(Python & Java & Golang)

TCO2014的编程赢取门票的题目,大致是从一个数组(大小为K),可以选取1~K个数,必须保证这n个数是从1~n,返回所有的选取方法个数。

思路:首先是得到从1开始连续的数,保存每个数的个数。然后通过排列组合得到结果。

当时采用的Python编写,大致的模样是这样(题目要求的类名就略去了):

 

def getNumber(type):    c = [0] * len(type)    s = 0    p = 0    for x in type:        if x <= len(type):            c[x-1] += 1    for i in c:        if i == 0:            return s        else:            if s == 0:                s = i                p = i            else:                p *= i                s += p    return sprint getNumber([2])print getNumber([1, 2])print getNumber([1, 3, 2])print getNumber([1, 1, 2])print getNumber([1, 3, 2, 5, 7, 4, 5, 4])print getNumber([1, 1, 2, 2, 3, 3, 4, 4, 5, 5])

 

之后尝试了一下 Java 版本:

package org.huys.algo.problem;public class WinterAndCandies {    public static int getNumber(int[] type) {        int[] c = new int[type.length];        int s = 0;        int p = 0;        for (int i=0; i<type.length; i++) {            if (type[i] <= type.length) {                c[type[i]-1] += 1;            }        }        for (int i=0; i<c.length; i++) {            if (c[i] == 0) {                return s;            } else {                if (s == 0) {                    s = c[i];                    p = c[i];                } else {                    p *= c[i];                    s += p;                }            }        }        return s;    }    public static void main(String[] args) {        System.out.println(getNumber(new int[] {2}));        System.out.println(getNumber(new int[] {1, 2}));        System.out.println(getNumber(new int[] {1, 3, 2}));        System.out.println(getNumber(new int[] {1, 1, 2}));        System.out.println(getNumber(new int[] {1, 3, 2, 5, 7, 4, 5, 4}));        System.out.println(getNumber(new int[] {1, 1, 2, 2, 3, 3, 4, 4, 5, 5}));    }}

 最近开始关注golang和swift,两种语言有很多共通之处。golang没有class,还是不免有些不适。

package mainimport "fmt"func getNumber(types []int) int {	var s = 0	var p = 0	var c = make([]int, len(types))	for _, value := range types {		if value <= len(types) {			c[value-1] += 1		}	}	for _, i := range c {		if i == 0 {			return s		} else {			if s == 0 {				s = i				p = i			} else {				p *= i				s += p			}		}	}	return s}func main() {    fmt.Println(getNumber([]int {2}))    fmt.Println(getNumber([]int {1, 2}))    fmt.Println(getNumber([]int {1, 3, 2}))    fmt.Println(getNumber([]int {1, 1, 2}))    fmt.Println(getNumber([]int {1, 3, 2, 5, 7, 4, 5, 4}))    fmt.Println(getNumber([]int {1, 1, 2, 2, 3, 3, 4, 4, 5, 5}))}

 代码中主要是数组相关操作。相对而言,Python 最灵活。Golang 中采用 Slice 语法,与同为C系语言的Java颇为接近。

 

GetNumber的实现(Python & Java & Golang)