iteye_13373 2008-09-09 20:46
浏览 269
已采纳

抢答题!!!

例如一个整型数组 int temp[] = {2,2,1,2,3,3,2}
其中2这个元素的个数大于了数组长度的一半,则称2为这个数组的“持重点”;
用程序算出给定这个数组的持重点是几,并返回它的所有下标;

[color=red][/color]
[b]问题补充:[/b]
怎么就会完全不明白呢?就拿这个数组来说,现在我们知道2是持重点,假如在不知道的情况下,让你求出来谁是持重点,并返回这个持重点的所有下标。
谁把程序写出来,我把仅有的积分全贡出去。

  • 写回答

4条回答 默认 最新

  • sptzone 2008-09-10 14:04
    关注

    [code="java"]import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;

    public class Test {

    public static void main(String[] args) {
        int temp[] = {2,2,1,2,3,3,2};
        int chiZhongDian = getChiZhongDian(temp);
    
        System.out.println("chiZhongDian:" + chiZhongDian);
    
        List appearList = getIndex(temp , chiZhongDian);
    
        System.out.println("index in Array:");
        for(Iterator itr = appearList.iterator();itr.hasNext();)
        {
            System.out.print(itr.next() + " ");
        }
    
    }
    
    public static List getIndex(int[] temp, int number)
    {
        List appearList = new ArrayList();
    
        for(int i = 0;i < temp.length;i ++)
        {
            if(temp[i] == number)
            {
                appearList.add(new Integer(i));
            }
        }
    
        return appearList;
    }
    
    public static int getChiZhongDian(int[] temp) {
        int size = temp.length;
    
        Map chiZhongDianMap = new HashMap();
        for (int i = 0; i < temp.length; i++) {
            if (chiZhongDianMap.get(new Integer(temp[i])) == null) {
                Integer eachCount = new Integer(1);
    
                chiZhongDianMap.put(new Integer(temp[i]), new Integer(1));
            } else {
                Integer eachCount = (Integer) chiZhongDianMap
                        .get(new Integer(temp[i]));
                eachCount = new Integer(eachCount.intValue() + 1);
                chiZhongDianMap.put(new Integer(temp[i]), eachCount);
            }
        }
    
        for(Iterator itr = chiZhongDianMap.keySet().iterator();itr.hasNext();)
        {
            Integer number = (Integer)itr.next();
            Integer eachCount = (Integer)chiZhongDianMap.get(number);
    
            if(eachCount.intValue() > (size / 2))
                return number.intValue();
        }
    
        throw new RuntimeException("Can not find ChiZhongDian");
    }
    

    }[/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效