zoukankan      html  css  js  c++  java
  • 数组的平衡点

    2007年5月去一个中小型外企的上机题,笔试全是英文的。没戏了。

    package myAction;
    public class Balence {
    /**
      * 求数组index左边的和
      * @param a
      * @param index
      * @return
      */
    public static int left(int[] a, int index)
    {
      int left = 0;
      if(index==0)
      {
       left = a[0];
       return left;
      }
      
      for(int i=0;i<index;i++)
      {
       left = left + a[index-1-i];
      }
      return left;
      
    }
    /**
      * 求数组右边的和
      * @param a
      * @param index
      * @return
      */
    public static int right(int[] a, int index)
    {
      
      int right = 0;
      if(index==a.length-1)
      {
       right = a[a.length-1];
       return right;
      }
      for(int i=index+1;i<a.length;i++)
      {
       right = right + a[i];
      }
      return right;
      
    }
    /**
      * 遍历数组,如果左边等于右边,则打印平衡点index
      * @param a
      */
    public static void balences(int a[])
    {
      int b[];
      int left = 0;
      int right = 0;
      int length = 0;
      for(int i=0;i<a.length;i++)
      {
       left = left(a,i);
       right = right(a,i);
       if(left==right)
       {
        length++;
        System.out.println("平衡点" + length + ":" + i);
       }
      
      }
      System.out.println("平衡点共计" + length + "个");
    } 
    

    //方法二
    //1. 先求總數.
    //X =A1+A2+A3+A4+..... +An
    //2. 從A1開始累加,設為N , 和等於(X-N)/2 為平衡點.
    //3. 一直找到數組最後
    //4.除于2后好像结果有点问题??

    public static void balence2(int[] a)
    {
      
      int sum = 0;
      int temp = 0;
      int length = 0;
      //求数组的总和
      for(int i=0;i<a.length;i++)
      {
       sum = sum + a[i];
      }
      for(int i=0;i<a.length;i++)
      {
       temp = temp + a[i];
       if(temp==((sum-temp)/2))
       {
        length++;
        System.out.println("平衡点" + length + ":" + i);
       }
      }
      System.out.println("平衡点共计" + length + "个");
    }
    
    //测试类
    public static void main(String[] args)
    {
      
      int[] a = {1,2,5,6,2,4,2,8};
      int left = left(a,3);
      int right = right(a,3);
    //  System.out.println("left=" + left);
    //  System.out.println("right=" + right);
      balences(a);
    //  balence2(a);
    }
    } 
    

  • 相关阅读:
    Java8 Stream Function
    PLINQ (C#/.Net 4.5.1) vs Stream (JDK/Java 8) Performance
    罗素 尊重 《事实》
    小品 《研发的一天》
    Java8 λ表达式 stream group by max then Option then PlainObject
    这人好像一条狗啊。什么是共识?
    TOGAF TheOpenGroup引领开发厂商中立的开放技术标准和认证
    OpenMP vs. MPI
    BPMN2 online draw tools 在线作图工具
    DecisionCamp 2019, Decision Manager, AI, and the Future
  • 原文地址:https://www.cnblogs.com/snandy/p/1964491.html
Copyright © 2011-2022 走看看