[LeetCode] 412. Fizz Buzz 解題報告

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]

這一題確實太簡單,沒什麼好說的,介紹兩種方法:

方法一:逐個判斷是不是3的倍數,5的倍數,15的倍數。需要說明的是,判斷條件的先後順序:可以把出現次是比較多的判斷條件儘量放前面,這樣可以減少判斷次數。

public class Solution {
	private static final String FIZZ = "Fizz";
	private static final String BUZZ = "Buzz";
	private static final String FIZZBUZZ = "FizzBuzz";

	public List<String> fizzBuzz(int n) {
		List<String> list = new ArrayList<>();
		int nCurrent = 0;
		while (nCurrent < n) {
			nCurrent++;
			if (nCurrent % 3 != 0 && nCurrent % 5 != 0) {
				list.add(String.valueOf(nCurrent));
				continue;
			}
			if (nCurrent % 15 == 0) {
				list.add(FIZZBUZZ);
				continue;
			}
			if (nCurrent % 3 == 0) {
				list.add(FIZZ);
				continue;
			}
			if (nCurrent % 5 == 0) {
				list.add(BUZZ);
				continue;
			}
		}
		return list;
	}
}

上面的continue,還可以用else if
方法二:先把所有的String用數字填滿,然後依次修改3的倍數,5的倍數,15的倍數。

public class Solution {
	private static final String FIZZ = "Fizz";
	private static final String BUZZ = "Buzz";
	private static final String FIZZBUZZ = "FizzBuzz";

	public List<String> fizzBuzz(int n) {
		List<String> list = new ArrayList<>();
		int nCurrent = 0;
		while (nCurrent < n) {
			nCurrent++;
			list.add(String.valueOf(nCurrent));
		}
		int nRadio = 1;
		while (nRadio * 3 <= n) {
			list.set(nRadio * 3 - 1, FIZZ);
			nRadio++;
		}
		nRadio = 1;
		while (nRadio * 5 <= n) {
			list.set(nRadio * 5 - 1, BUZZ);
			nRadio++;
		}
		nRadio = 1;
		while (nRadio * 15 <= n) {
			list.set(nRadio * 15 - 1, FIZZBUZZ);
			nRadio++;
		}
		return list;
	}
}
下面是以上代碼的速度上的改進,不是直接用的list,而是使用的String數組,最後轉成list:

public class Solution {
	private static final String FIZZ = "Fizz";
	private static final String BUZZ = "Buzz";
	private static final String FIZZBUZZ = "FizzBuzz";

	public List<String> fizzBuzz(int n) {
		String[] strArr = new String[n];
		List<String> list = new ArrayList<>();
		for (int i = 0; i < strArr.length; i++) {
			strArr[i] = String.valueOf(i+1);
		}
		int nRadio = 1;
		while (nRadio * 3 <= n) {
			strArr[nRadio * 3 - 1] = FIZZ;
			nRadio++;
		}
		nRadio = 1;
		while (nRadio * 5 <= n) {
			strArr[nRadio * 5 - 1] = BUZZ;
			nRadio++;
		}
		nRadio = 1;
		while (nRadio * 15 <= n) {
			strArr[nRadio * 15 - 1] = FIZZBUZZ;
			nRadio++;
		}
		return Arrays.asList(strArr);
	}
}

總結:理論上,兩個方法複雜度的數量級一樣,都是O(n),但是方法二在係數上要大於方法一,因此要慢一點。做了改進以後,方法二的速度有了少許的提高。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章