Topcoder 练习小记,Java 与 Python 分别实现。

Topcoder上的一道题目,题目描述如下:

Problem Statement
    
Byteland is a city with many skyscrapers, so it‘s a perfect venue for BASE jumping. Danilo is an enthusiastic BASE jumper. He plans to come to Byteland and to jump off some of its buildings.

Danilo wants to make M jumps in Byteland. However, he has some rules. First, he never jumps off the same building twice. Second, all buildings he selects for his jumps must have the same number of floors. (This is for safety reasons: It is hard to get the timing right if each jump starts at a different height.)

Philipe is the mayor of Byteland. He welcomes Danilo‘s visit as he would like to use it as a publicity stunt. However, Philipe knows that Danilo will only come to Byteland if there are at least M buildings that each have the same number of floors. To ensure that, the mayor is willing to build additional floors on some of the skyscrapers in Byteland.

You are given the int M and a int[] heights. Each element of heights is the number of floors in one of Byteland‘s skyscrapers. Compute and return the smallest number of additional floors the mayor has to build so that there will be at least M buildings with the same number of floors.
Definition
    
Class:
BuildingHeightsEasy
Method:
minimum
Parameters:
int, int[]
Returns:
int
Method signature:
int minimum(int M, int[] heights)
(be sure your method is public)
Limits
    
Time limit (s):
2.000
Memory limit (MB):
256
Constraints
-
heights will contain between 1 and 50 elements, inclusive.
-
M will be between 1 and the number of elements in heights, inclusive.
-
Each element in heights will be between 1 and 50, inclusive.
Examples
0)

    
2
{1, 2, 1, 4, 3}
Returns: 0
Note that we already have two buildings that have the same number of floors. Hence, no additional floors need to be built.
1)

    
3
{1, 3, 5, 2, 1}
Returns: 2
We want to have at least three buildings with the same number of floors. The best way to reach this goal is to build one floor on building #0 and one floor on building #4 (0-based indices). After these changes, buildings #0, #3, and #4 will have two floors each.
2)

    
1
{43, 19, 15}
Returns: 0

3)

    
3
{19, 23, 9, 12}
Returns: 15

4)

    
12
{25, 18, 38, 1, 42, 41, 14, 16, 19, 46, 42, 39, 38, 31, 43, 37, 26, 41, 33, 37, 45, 27, 19, 24, 33, 11, 22, 20, 36, 4, 4}
Returns: 47

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.

题目意思是给定一堆楼高度的 List 为 heights ,需要在这些楼里选择 M 栋高度相同的楼,如果没够足够相同高度的楼,就加高一些楼层使得满足需求。求至少需要加高多少层数楼。

最直接的解题思路:

排序所有楼层,分别计算加高到某一楼层需要的总层数,取出其中最少的数字。

假设所有楼层有:{19, 23, 9, 12} 4栋楼。要在其中取 M= 3 栋相同的楼层,排序后的序列为:

{9, 12, 19, 23}

则从第 3 栋开始考虑增加楼层,即将 9, 12 增加至 19 , 共需增加 19*3 - (9 + 12 + 19) = 17 层

在第 4 栋楼层(23)开始增加:共需增加 23*3 - (12 + 19 + 23) = 15 层

答案是 15

Java 写的实现:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BuildingHeightsEasy {

    public static void main(String[] args) {
        BuildingHeightsEasy bh = new BuildingHeightsEasy();
        int M = 3;
        int[] heights = {19, 23, 9, 12} ;
        int total = bh.minimum(M, heights);
        System.out.println(total);
    }

    public int minimum(int M, int[] heights) {
        if (M == 1) {
            return 0;
        }
        List<Integer> list = new ArrayList<Integer>();
        for (Integer cost : heights) {
            list.add(cost);
        }
        Collections.sort(list);
        Integer total = Integer.MAX_VALUE;
        for (int i = M - 1; i < list.size(); i++) {
            int sum = getSumValue(M, i, list);
            if (sum < total) {
                total = sum;
            }
        }
        return total;
    }

    public int getSumValue(int M, int end, List<Integer> list) {
        int sum = 0;
        for (int i = end - M + 1; i < end + 1; i++) {
            sum += list.get(i);
        }
        int value = list.get(end);
        return value * M - sum;
    }
}

Java 在 int 数组转换为 List 和 sum List 值等方便会比较繁琐。

Python 的实现:

class BuildingHeightsEasy(object):
    def minimum(self, M, heights):
        if M == 1 : return 0
        heights = list(heights)
        heights.sort()
        total = M * heights[len(heights)-1]
        for i in range(M-1,len(heights)):
            sumValue = M * heights[i] - sum(heights[i-M+1:i+1])
            total =  sumValue if sumValue < total else total

        return total

M = 3
heights = (19, 23, 9, 12)

bh = BuildingHeightsEasy()
print bh.minimum(M,heights)

Python 内置了很丰富的函数,特别是 sum 函数和 list 的切片功能。

结语留空。

Topcoder 练习小记,Java 与 Python 分别实现。

时间: 2024-10-01 06:54:43

Topcoder 练习小记,Java 与 Python 分别实现。的相关文章

java与python在处理大文件操作上的对比

1.问题描述 现在对一个2g的大文件,抽取第二列含有特点16个串的信息,并将这些含有特串的信息,写回到两个文件中 2.具体实现 (1)java代码 package naifen; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java

fasttext的基本使用 java 、python为例子

fasttext的基本使用 java .python为例子 今天早上在地铁上看到知乎上看到有人使用fasttext进行文本分类,到公司试了下情况在GitHub上找了下,最开始是c++版本的实现,不过有Java.Python版本的实现了,正好拿下来试试手, python情况: python版本参考,作者提供了详细的实现,并且提供了中文分词之后的数据,正好拿下来用用,感谢作者,代码提供的数据作者都提供了,点后链接在上面有百度盘,可下载,java接口用到的数据也一样: [html] view plai

利用thrift在c++、java和python之间相互调用

转自:http://blog.csdn.net/andy_yf/article/details/7487384 thrift做为跨语言调用的方案有高效,支持语言较多,成熟等优点:代码侵入较强是其弱点. 下面记录以C++做服务器,C++,java和python做客户端的示例,这个和本人现在工作环境吻合,使用多线程长连接的socket来建立高效分布式系统的跨语言调用平台.遗憾的是目前版本(0.7.0)的C语言还不支持Compact协议,导致在现在的环境中nginx c module调用thrift要

ubuntu上用eclipse搭建java、python开发环境

上一篇文章讲到如何在windwos上用eclipse搭建java.python开发环境,这一讲将关注如何在ubuntu上实现搭建,本人使用虚拟机安装的ubuntu系统,系统版本为:14.04 lts 一.用eclipse + jdk搭建java开发环境 1.jdk官方下载地址:http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html 本人下载的是:jdk-8u77-linux-x64.tar.gz

Java vs. Python (1): Simple Code Examples

Some developers have claimed that Python is more productive than Java. It is dangerous to make such a claim, because it may take several days to prove that thoroughly. From a high level view, Java is statically typed, which means all variable names h

Java vs Python

面试时常问到这两种语言的区别,在此总结一下. Referrence: Udemy:python-vs-java Generally, Python is much simpler to use, and more compact than Java. It is generally easier to learn, and more forgiving when it comes to using shortcuts like reusing an old variable. You will

C/C++、Java、Python谁是编译型语言,谁是解释型语言?

最近各大互联网公司线上笔试,编程题目里的编译器只支持C/C++.Java,甚至有的支持javaScrpit和Pascal,就是不支持Python.让一直以来用惯了Python的我直吐血,于是今天痛定思痛还是熟悉一下Java,免得继续被虐.学习的过程中,看到这样一个争论“Java.Python谁是编译型语言,谁是解释性语言?”.我在网上查了很多资料,也结合了自己的理解,下面与大家分享一下. 总的来说,如今编译型语言.解释性语言的分界线不再那么明显,应该避免把语言简单归类为“编译型”和“解释型”.

Java与Python下载Bing首页图片

Java与Python下载Bing首页图片 一,首先是Java代码 import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache

Java 和 Python 的 Socket 通信

网络上两个程序通过一个双向通讯连接实现数据的交换,这个双向链路的一端称为一个Socket.Socket支持的协议有多种,这里主要介绍基于 TCP/IP 协议族的 Socket 编程. 首先,IP协议族决定了socket的地址类型,在通信中必须采用对应的地址.AF_INET(AF 表示 Adress Family)表示要用 ipv4 地址(32位)与端口号(16位)的组合. 然后,根据传输协议又分为:流式 Socket(SOCK_STREAM) 和数据报式 Socket(SOCK_DGRAM):