100例java算法的简单介绍

博主:adminadmin 2023-03-20 19:24:10 313

本篇文章给大家谈谈100例java算法,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java面试有哪些算法

面试-java算法题:

1.编写一个程序,输入n,求n!(用递归的方式实现)。

public static long fac(int n){ if(n=0) return 0; else if(n==1) return 1; else return n*fac(n-1);

} public static void main(String [] args) {

System.out.println(fac(6));

}

2.编写一个程序,有1,2,3,4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

public static void main(String [] args) { int i, j, k; int m=0; for(i=1;i=4;i++) for(j=1;j=4;j++) for(k=1;k=4;k++){ if(i!=jk!=ji!=k){

System.out.println(""+i+j+k);

m++;

}

}

System.out.println("能组成:"+m+"个");

}

3.编写一个程序,将text1.txt文件中的单词与text2.txt文件中的单词交替合并到text3.txt文件中。text1.txt文件中的单词用回车符分隔,text2.txt文件中用回车或空格进行分隔。

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

public class text{

public static void main(String[] args) throws Exception{

String[] a = getArrayByFile("text1.txt",new char[]{'\n'});

String[] b = getArrayByFile("text2.txt",new char[]{'\n',' '});

FileWriter c = new FileWriter("text3.txt");

int aIndex=0; int bIndex=0;

while(aIndexa.length){

c.write(a[aIndex++] + "\n");

if(bIndexb.length)

c.write(b[bIndex++] + "\n");

}

while(bIndexb.length){

c.write(b[bIndex++] + "\n");

}

c.close();

}

public static String[] getArrayByFile(String filename,char[] seperators) throws Exception{

File f = new File(filename);

FileReader reader = new FileReader(f);

char[] buf = new char[(int)f.length()];

int len = reader.read(buf);

String results = new String(buf,0,len);

String regex = null;

if(seperators.length 1 ){

regex = "" + seperators[0] + "|" + seperators[1];

}else{

regex = "" + seperators[0];

}

return results.split(regex);

}

}

4.639172每个位数上的数字都是不同的,且平方后所得数字的所有位数都不会出现组成它自身的数字。(639172*639172=408540845584),类似于639172这样的6位数还有几个?分别是什么?

这题采用的HashMap结构判断有无重复,也可以采用下题的数组判断。

public void selectNum(){

for(long n = 100000; n = 999999;n++){

if(isSelfRepeat(n)) //有相同的数字,则跳过

continue;

else if(isPingFangRepeat(n*n,n)){ //该数的平方中是否有与该数相同的数字

continue;

} else{ //符合条件,则打印 System.out.println(n);

}

}

} public boolean isSelfRepeat(long n){

HashMapLong,String m=new HashMapLong,String(); //存储的时候判断有无重复值

while(n!=0){ if(m.containsKey(n%10)){ return true;

} else{

m.put(n%10,"1");

}

n=n/10;

} return false;

} public boolean isPingFangRepeat(long pingfang,long n){

HashMapLong,String m=new HashMapLong,String(); while(n!=0){

m.put(n%10,"1");

n=n/10;

} while(pingfang!=0){ if(m.containsKey(pingfang%10)){ return true;

}

pingfang=pingfang/10;

} return false;

} public static void main(String args[]){ new test().selectNum();

}

5.比如,968548+968545=321732732它的答案里没有前面两个数里的数字,有多少这样的6位数。

public void selectNum(){

for(int n = 10; n = 99;n++){

for(int m = 10; m = 99;m++){ if(isRepeat(n,m)){ continue;

} else{

System.out.println("组合是"+n+","+m);

}

}

}

} public boolean isRepeat(int n,int m){ int[] a={0,0,0,0,0,0,0,0,0,0}; int s=n+m; while(n!=0){

a[n%10]=1;

n=n/10;

} while(m!=0){

a[m%10]=1;

m=m/10;

} while(s!=0){ if(a[s%10]==1){ return true;

}

s=s/10;

} return false;

} public static void main(String args[]){ new test().selectNum();

}

6.给定String,求此字符串的单词数量。字符串不包括标点,大写字母。例如 String str="hello world hello hi";单词数量为3,分别是:hello world hi。

public static void main(String [] args) { int count = 0;

String str="hello world hello hi";

String newStr="";

HashMapString,String m=new HashMapString,String();

String [] a=str.split(" "); for (int i=0;ia.length;i++){ if(!m.containsKey(a[i])){

m.put(a[i],"1");

count++;

newStr=newStr+" "+a[i];

}

}

System.out.println("这段短文单词的个数是:"+count+","+newStr);

}

7.写出程序运行结果。

public class Test1 { private static void test(int[]arr) { for (int i = 0; i arr.length; i++) { try { if (arr[i] % 2 == 0) { throw new NullPointerException();

} else {

System.out.print(i);

}

} catch (Exception e) {

System.out.print("a ");

} finally {

System.out.print("b ");

}

}

}

public static void main(String[]args) { try {

test(new int[] {0, 1, 2, 3, 4, 5});

} catch (Exception e) {

System.out.print("c ");

}

}

}

运行结果:a b 1b a b 3b a b 5b

public class Test1 { private static void test(int[]arr) { for (int i = 0; i arr.length; i++) { try { if (arr[i] % 2 == 0) { throw new NullPointerException();

} else {

System.out.print(i);

}

}

finally {

System.out.print("b ");

}

}

}

public static void main(String[]args) { try {

test(new int[] {0, 1, 2, 3, 4, 5});

} catch (Exception e) {

System.out.print("c ");

}

}

}

运行结果:b c

8.单词数

统计一篇文章里不同单词的总数。

Input

有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束。

Output

每组值输出一个整数,其单独成行,该整数代表一篇文章里不同单词的总数。

Sample Input

you are my friend

#

Sample Output

4

public static void main(String [] args) {

ListInteger countList=new ArrayListInteger(); int count;

HashMapString,String m;

String str; //读取键盘输入的一行(以回车换行为结束输入) String[] a;

Scanner in=new Scanner(System.in);

while( !(str=in.nextLine()).equals("#") ){

a=str.split(" ");

m=new HashMapString,String();

count = 0; for (int i=0;ia.length;i++){ if(!m.containsKey(a[i]) (!a[i].equals(""))){

m.put(a[i],"1");

count++;

}

}

countList.add(count);

}s for(int c:countList)

System.out.println(c);

}

java算法有哪些分别

您好:

java中的算法,常见的有:递归、迭代、查找、排序(包含冒泡排序、选择排序、插入排序、快速排序四种) 等,算法有很多,一般数据结构中涉及到的都可以用java语言实现。

举几个例子:

1.递归的例子:

2.排序的例子:

不一一举例,仅供参考!

求一段JAVA的概率算法

public class Zhuq {

public static void main(String[] args) {

ListPerson listP=new ArrayListPerson();

listP.add(new Person("小李", "1", 200));

listP.add(new Person("小王", "2", 210));

listP.add(new Person("小赵", "3", 230));

listP.add(new Person("小孙", "4", 100));

listP.add(new Person("小钱", "5", 3));

listP.sort(new ComparatorPerson() {

@Override

public int compare(Person o1, Person o2) {

// TODO Auto-generated method stub

return (((Person)o1).count)*(Math.random()*10+1)(((Person)o2).count)*(Math.random()*10+1)?-1:1;

}

});

System.out.println(listP);

}

}

class Person {

String personName;

String id;

int count;

public Person(String personName, String id, int count) {

super();

this.personName = personName;

this.id = id;

this.count = count;

}

@Override

public String toString() {

return "Person [personName=" + personName + ", id=" + id + ", count=" + count + "]";

}

}

//本质还是随机数

JAVA 100个数字用算法排序

class SortTest { // 冒泡排序

    public void sort(int[] args) {

 

        for (int m : args) {

            System.out.print("排序前 " + args[m] + " ");

        }

 

        int time1 = 0, time2 = 0;

        for (int i = 0; i  args.length - 1; i++) {

            ++time1;

            for (int j = i + 1; j  args.length; j++) {

                ++time2;

                int temp;

                if (args[i]  args[j]) {

                    temp = args[j];

                    args[j] = args[i];

                    args[i] = temp;

                }

            }

        }

        System.out.println();

        System.out.println("外循环次数:" + time1 + "内循环次数:" + time2);

        for (int n : args) {

            System.out.print("排序后 " + n + " ");

        }

    }

 

    public static void main(String[] args) {

        int[] arg = new int[] { 2, 1, 4, 5, 8, 7, 6, 3, 9, 0 };

        new SortTest().sort(arg);

    }

}

// 降序排列 循环次数最少

// 输出结果为:

// 排序前 4 排序前 1 排序前 8 排序前 7 排序前 9 排序前 3 排序前 6 排序前 5 排序前 0 排序前 2

// 外循环次数:9 内循环次数:45

// 排序后 0 排序后 1 排序后 2 排序后 3 排序后 4 排序后 5 排序后 6 排序后 7 排序后 8 排序后 9

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

import java.util.Random;

/**

 * class name: RapidSort

 * description: Java快速排序法:数组和集合

 * @author Jr

 *

 */

public class RapidSort {

    public static void QuickSort(int e[], int first, int end) {

        int i = first, j = end, temp = e[first];

        while (i  j) {

            while (i  j  e[j] = temp)

                j--;

            e[i] = e[j];

            while (i  j  e[i] = temp)

                i++;

            e[j] = e[i];

        }

        e[i] = temp;

        if (first  i - 1)

            QuickSort(e, first, i - 1);

        if (end  i + 1)

            QuickSort(e, i + 1, end);

    }

    public static void main(String[] args) {

        int arr[] = { 49, 38, 65, 97, 76, 13, 27, 49 };

        int len = 8;

        int i;

        System.out.printf("before sort\n");

        for (i = 0; i  len; i++)

            System.out.printf("%d  ", arr[i]);

        System.out.printf("\n");

        QuickSort(arr, 0, len - 1);

        System.out.printf("after sorted\n");

        for (i = 0; i  len; i++)

            System.out.printf("%d  ", arr[i]);

    }

}

结果:

before sort

49  38  65  97  76  13  27  49  

after sorted

13  27  38  49  49  65  76  97

java递归算法的例子。

阶乘:

要求:给定一个数值,计算出它的阶乘值,例如5的阶乘为5*4*3*2*1

实现:

[html] view plaincopy

span style="font-size:12px;"  // 利用递归实现一个数的阶乘值      private static BigDecimal getNum(BigDecimal inNum) {          if (inNum.compareTo(BigDecimal.ONE) == 0) {              return inNum;          }          return inNum.multiply(getNum(inNum.subtract(BigDecimal.ONE)));      }/span

(2)Fibonacci数列:1,1,2,3,5,8,13……

要求:找出数列中指定index位置的数值

实现:

[html] view plaincopy

span style="font-size:12px;"  // 利用递归实现了Fibonacci数列      private static int fab(int index) {          if (index == 1 || index == 2) {              return 1;          } else {              return fab(index - 1) + fab(index - 2);          }      }/span

(3)汉诺塔

要求:汉诺塔挪动

实现:

[html] view plaincopy

span style="font-size:12px;"  span style="white-space:pre;" /spanprivate static final String DISK_B = "diskB";    span style="white-space:pre;"   /spanprivate static final String DISK_C = "diskC";    span style="white-space:pre;"   /spanprivate static final String DISK_A = "diskA";    span style="white-space:pre;"   /spanstatic String from=DISK_A;  span style="white-space:pre;" /span  static String to=DISK_C;  span style="white-space:pre;" /span  static String mid=DISK_B;    span style="white-space:pre;" /span  public static void main(String[] args) {  span style="white-space:pre;" /span      String input=JOptionPane.showInputDialog("please input the number of the disks you want me move.");  span style="white-space:pre;" /span      int num=Integer.parseInt(input);  span style="white-space:pre;" /span      move(num,from,mid,to);  span style="white-space:pre;" /span  }/span

[html] view plaincopy

span style="font-size:12px;"  // 利用递归实现汉诺塔      private static void move(int num, String from2, String mid2, String to2) {          if (num == 1) {              System.out.println("move disk 1 from " + from2 + " to " + to2);          } else {              move(num - 1, from2, to2, mid2);              System.out.println("move disk " + num + " from " + from2 + " to " + to2);              move(num - 1, mid2, from2, to2);          }      }/span

(4)排列组合

要求:将输入的一个字符串中的所有元素进行排序并输出,例如:你给出的参数是"abc",

则程序会输出

abc

acb

bac

bca

cab

cba

实现:

[html] view plaincopy

span style="font-size:12px;"span style="white-space:pre;"   /spanpublic static void permute(String str) {   span style="white-space:pre;"    /span   char[] strArray = str.toCharArray();    span style="white-space:pre;"   /span permute(strArray, 0, strArray.length - 1);  span style="white-space:pre;" /span}/span

[html] view plaincopy

span style="font-size:12px;"  // 利用递归实现,将输入的一个字符串中的所有元素进行排序并输出      public static void permute(char[] list, int low, int high) {          int i;          if (low == high) {              String cout = "";              for (i = 0; i = high; i++) {                  cout += list[i];              }              System.out.println(cout);          } else {              for (i = low; i = high; i++) {                  char temp = list[low];                  list[low] = list[i];                  list[i] = temp;                  permute(list, low + 1, high);                  temp = list[low];

java递归算法的例子?

简单理解一下:

递归就是调用上一步的结果,来产生下一步的结果,一般上一步的结果是由函数得到,所以下一步直接调用函数,参数不一样而已:

阶乘算法:

public int JieCheng(int n){

return n*JieCheng(n-1);

}

当然还必要一些条件判断吗,就是终止递归调用的,jiecheng为n=1 时 就return 1;

关于100例java算法和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。