網易有道比賽第二道題目解法(java)

來源:互聯網
上載者:User

Problem Statement
????
雙倍超立方數是指一個正整數可以正好被拆分為兩種不同的a^3+b^3的方式,其中a,b均為整數且0<a<=b。對於任何一個指定的 int n, 返回所有的小於等於n的雙倍超立方數的個數。
Definition
????
Class:
TwiceSuperCubic
Method:
count
Parameters:
int
Returns:
int
Method signature:
int count(int n)
(be sure your method is public)
????

Constraints
-
n取值範圍為1到1,000,000,000(含)
Examples
0)

????
1
Returns: 0

1)

????
1729
Returns: 1
1729=1^3+12^3 1729=9^3+10^3
2)

????
475574
Returns: 27

 

 

 

 

import java.util.Arrays;
import java.util.Vector;

public class Second {
 public static void main(String[] args) {
  Second s = new Second();
  long st = System.currentTimeMillis();
  System.out.println(s.count(475574));
  System.out.println(System.currentTimeMillis() - st);
 }

 public int count(int number) {
  Vector<Integer> vec = new Vector<Integer>();
  int max = (int) Math.cbrt(number);
  for (int i = 1; i <= max; i++) {
   for (int j = max; j > i; j--) {
    int temp = addThree(i, j);
    if (temp <= number) {
     vec.add(new Integer(temp));
    }
   }
  }
  int size = vec.size();
  int result[] = new int[size];
  for (int i = 0; i < size; i++) {
   result[i] = vec.elementAt(i).intValue();
  }

  Arrays.sort(result);

  int count = 0;
  for (int i = 0; i < result.length;) {
   int n = countNumber(result, i);
   if (n == 2) {
    count++;
   }
   i += n;
  }

  return count;
 }

 public int addThree(int a, int b) {
  return a * a * a + b * b * b;
 }

 public int countNumber(int[] array, int st) {
  int number = 1;
  int len = array.length;
  for (int i = st + 1; i < len; i++) {
   if (array[i] == array[st]) {
    number++;
   }
  }
  return number;
 }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.