Java算法面试题 一个顺子带一对

打牌里面经常出现的5张牌,一个顺子带一对,给你五张牌,比如:1,2,2,2,3 或者 5,6,7,4,4 或者 2,4,3,5,5 或者 7,5,9,6,9 ,这种情况就符合一个顺子带一对,则返回 true;反之比如:1,3,4,6,6 或者 1,5,5,3,4 这种返回false,请你在不能使用任何数组原生方法,只能使用循环和赋值的情况下完成。

public class test7 {
    //判断是否为一个顺子带一对的方法
        public static boolean test(int [] a) {
            int index = -1;//用来记录对子中第一个元素的下标
            int [] sequence = new int [a.length-2];//用来存放顺子
            
            //首先对数组进行排序,这里使用的选择排序
            selectSort(a);
            
            //将数组从小到大排好序后,双重循环找到重复元素出现的下标
            for (int i = 0; i < a.length; i++) {
                for (int j = 0; j < a.length-1; j++) {
                    if(a[j+1]==a[j]) {
                        index = j;
                    }
                }
            }
            
            //根据下标,去除一个对子,将剩下的元素存放到一个新的数组,这个数组仍然是有序的
            for (int i = 0,j=0; i < a.length; i++) {
                if(i!=index&&i!=(index+1)) {
                    sequence[j] = a[i];
                    j++;
                }
            }
            
            //调用判断是否为顺子的方法
            return isSequence(sequence);
        }
        
        //选择排序的方法
        public static void selectSort(int [] a) {
            for (int i = 0; i < a.length; i++) {
                for (int j = 0; j < a.length-1; j++) {
                    if(a[j+1]<a[j]) {
                        int temp = a[j];
                        a[j] = a[j+1];
                        a[j+1] = temp;
                    }
                }
            }
        }
        
        //判断是否为顺子的方法
        public static boolean isSequence(int [] a) {
            boolean flag = true;
            for (int i = 0; i < a.length-1; i++) {
                if(a[i+1]-a[i]!=1) {
                    flag =  false;
                    break;
                }
            }
            return flag;
        }
        
        //主方法测试,成功
        public static void main(String[] args) {
            int [] a1 = {1,2,2,2,3,4};
            int [] a2 = {5,6,7,4,4};
            int [] a3 = {2,4,3,5,5};
            int [] a4 = {7,5,9,6,9};
            int [] a5 = {1,5,5,3,4};
            int [] a6 = {2,1,3,4,6,6};
            
            System.out.println(test(a1) == true? "顺子加对子":"非顺子加对子");
            System.out.println(test(a2)== true? "顺子加对子":"非顺子加对子");
            System.out.println(test(a3)== true? "顺子加对子":"非顺子加对子");
            System.out.println(test(a4)== true? "顺子加对子":"非顺子加对子");
            System.out.println(test(a5)== true? "顺子加对子":"非顺子加对子");
            System.out.println(test(a6)== true? "顺子加对子":"非顺子加对子");
        }
    }
View Code
原文地址:https://www.cnblogs.com/xiangpeng/p/10468985.html