`
where
  • 浏览: 80840 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

实习路上的各种题(2)

阅读更多

题目:

“编写函数int[]alphaOrder(int n),返回按字典排序的数字1~n”

例如n=12,返回[1,10,11,12,2,3,4,5,6,7,8,9]

      当时一看这题有点蒙了,首先过分纠结于“字典排序“这几个字眼,而忽略了题目本身,导致当时我这个题目尽然空着。下来再想想这个题目其实单纯从给出一个答案的角度看真不难。

先上一段我实现的代码:

 

public class AlphaOrder {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		AlphaOrder ao = new AlphaOrder();
		int[] result =  ao.alphaOrder(12);
		for(int i =0;i<result.length;i++){
			System.out.print(result[i]+",");
		}

	}
	/**
	 * 传入一个数作为数组长度,产生一个字典排序后的数组
	 * @param n
	 * @return
	 */
	private int[] alphaOrder(int n){
		int [] a = new int[n];
		String [] temp = new String[n];//作为中间数组
		String s;
		
		//生成原始数组
		for(int i=1;i<=n;i++){
			temp[i-1] =""+i;
		}
		//借用String的CompareTo()方法进行字典排序
                //这里用两个层嵌套不好,针对本题对有规律的整型数排序一层就够
                //这样时间复杂度可以由O(n2)减为O(n)
		for(int i=0;i<temp.length;i++){
			for(int j = 1;j<temp.length;j++){
				int com = temp[j].compareTo(temp[j-1]);
				System.out.println(temp[j]+"compareTo"+temp[j-1]+"的结果是:"+temp[j].compareTo(temp[j-1]));
				if(com<0){
					s=temp[j-1];
					temp[j-1] = temp[j];
					temp[j] = s;
				}
			}
		}
		//将字符串数组转化成整型数组
		for(int i = 0;i<n;i++){
			a[i] = Integer.parseInt(temp[i]);
		}
		return a;
		
	}

}

 测试的结果:

 

 

1,10,11,12,2,3,4,5,6,7,8,9

 谈谈对这个题的思考:

 

        这个体大的不好就在于一点就是”纠结于怎么实现”字典排序“,而忽略了String类已经为我们提供了这样  的方法“后来我又想了想,导致这个状况可能有这么几个原因:

      1)开始的思路是不对的当时压根就没往这方面想

      2)在学习的时候做的不够细,手边常用的还行,那些做项目中没接触过的可能就不那么熟悉,就比如”字典排序“String的”compareTo“方法,可能就局限与知道,连熟悉可能都谈不上。

public int compareTo(String anotherString) {
      int len1 = count;
      int len2 = anotherString. count;
      int n = Math. min(len1, len2);
      char v1[] = value;
      char v2[] = anotherString. value;
      int i = offset;
      int j = anotherString. offset;

      if (i == j) {
         int k = i;
         int lim = n + i;
         while (k < lim) {
           char c1 = v1[k];
           char c2 = v2[k];
           if (c1 != c2) {
              return c1 - c2;
          }
          k++;
         }
     } else {
         while (n-- != 0) {
           char c1 = v1[i++];
           char c2 = v2[j++];
           if (c1 != c2) {
              return c1 - c2;
          }
         }
     }
      return len1 - len2;
    }

 

      3)看源码,可能对一些常用类的方法平时我就只局限于用的程度,没有认真地想想或看看具体的实现,以后在这方面可能会多留心,尽量做到"不仅知其然还要知其所以然"

      4)  前路漫漫,任重道远,加油吧”少年“时间不早了就先写到这(晚安,各位看官!!!)

 

 

 

 

 

 

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics