First they ignore you
          then they ridicule you
          then they fight you
          then you win
              -- Mahatma Gandhi
          Chinese => English     英文 => 中文             
          隨筆-221  評論-1047  文章-0  trackbacks-0
          ??????? 每個問題有很多種解法,但其中存在一種最優的算法,據我觀察和思考,‘懶人’是寫不出那種最優算法的,為什么呢?因為最優算法有一個很明顯的特點就是算法本身集結了人類的聰明才智,讓我來用一個實例來證明這個觀點:

          問題:
          請計算當參數為 n(n很大) 時, 1-2+3-4+5-6+7+......+n 的值

          ‘懶人’解法:
          public class Lazy {
          ? public static void main(String[] args) {
          ??? int n = 10000;
          ??? int result = 0;
          ??? for (int i = 0, flag = 1; i < n; i++) {
          ????? result += flag * (i + 1);
          ????? flag =?-flag;
          ??? }
          ??? System.out.println(result);
          ? }
          }

          ‘勤人’解法:
          public class Diligent {
          ? public static void main(String[] args) {
          ??? int n = 10000;
          ??? int result = 0;
          ??? if (0 == n % 2) {
          ????? result = -n / 2;
          ??? } else {
          ????? result = -n / 2 + n;? //由于-n / 2會舍棄小數部分,所以無需寫成-(n - 1) / 2
          ??? }
          ??? System.out.println(result);
          ? }
          }

          人類的智慧為計算機擔負了不少的計算量,“懶人”算法的時間復雜度為O(n),而“勤人”算法的時間復雜度僅為O(1),這題的最優算法出世了!
          忠告各位喜愛編程的朋友,在解決問題之前,請可憐可憐您使用的那臺精疲力盡的計算機吧,花些時間思考一下,您付出的一分一秒都會有回報的 :-)
          posted on 2006-10-14 18:05 山風小子 閱讀(1565) 評論(10)  編輯  收藏 所屬分類: Algorithm
          主站蜘蛛池模板: 荥经县| 无为县| 原阳县| 株洲市| 当雄县| 海阳市| 资阳市| 平和县| 西城区| 绍兴市| 酒泉市| 明溪县| 建水县| 石柱| 邵武市| 松江区| 宁阳县| 濉溪县| 高邮市| 铜山县| 西贡区| 南投县| 哈巴河县| 巴彦县| 紫云| 迭部县| 淮阳县| 平度市| 疏附县| 怀集县| 镇沅| 西林县| 沧州市| 泌阳县| 隆德县| 纳雍县| 清苑县| 多伦县| 鄂托克前旗| 唐河县| 海丰县|