Java——数组相关编程练习

/*
 * 数组相关的题
 */

import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

public class Solution_intarray {
    public static void main(String[] args) {
//        int i=0;
//        Integer j = new Integer(0);
//        System.out.println(i==j);
//        System.out.println(j.equals(i));
//        
//        List  Listlist1 = new ArrayList();
//        Listlist1.add(0);
//        List Listlist2 = Listlist1;
//        System.out.println(Listlist1.get(0) instanceof Integer);
//        System.out.println(Listlist2.get(0) instanceof Integer);
        
        //二位数组的声明
//        int arr[][] = new int[10][10];  //t
//        int []arr1[] = new int[10][10]; //t
//        int b[10][10] = new int[][];  //f
//        int a[][] new int[][];  //f
        
        //int[][] arr={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
//        int[][] arr={{1,2},{5,6},{9,10},{13,14},{15,16}};
//        //int[][] arr={{1},{5},{9},{13}};
//        //int[] arr1 = {1};
//        ArrayList<Integer> list1 = printMatrix(arr);
//        System.out.println(list1.toString());
//        double res = Power(2,-3);
//        System.out.println(res);
        
        //System.out.println( << 1);
//        int[] arr = {1,2,3,4,5,6,7};
//        reOrderArray(arr);
//        int[] arr = {4,5,1,6,2,7,3,8};
//        int k = 10;
//        ArrayList<Integer> limin = GetLeastNumbers_Solution(arr,k);
//        System.out.println(limin.toString());
        
//        int[] arr = {1,-2,3,10,-4,7,2,-5};
//        System.out.println(FindGreatestSumOfSubArray(arr));
//        int count = NumberOf1Between1AndN_Solution(13);
//        System.out.println(count);
        
//        int[] number = {3,32,321};
//        System.out.println(PrintMinNumber(number));
        
//        System.out.println(GetUglyNumber_Solution(0));
        
//        int flag = 1;
//        for(int i = 0; i<4 ;i++){
//            flag <<=1;
//            System.out.println(flag);
//        }
        
//        int[] arr = {1,2,3,4,3,2};
//        int[] num1 = {0};
//        int[] num2 = {0};
//        FindNumsAppearOnce(arr,num1,num2);
//        System.out.println(num1[0]);
//        System.out.println(num2[0]);
        
//        int[] arr = {1,2,3,4,5,6,7,0};
//        System.out.println(InversePairs(arr));
        
//        mystery(1234);
        int[] A = {1,2,3,4,5};
        int[] B = multiply(A);
        for(int i = 0;i < B.length ;i++)
            System.out.print(B[i]+" ");
    }
    
    public static void mystery (int x){
        System.out.print(x % 10);
     
        if ((x / 10) != 0){
            mystery(x / 10);
            }
        System.out.print(x % 10);
    }
    
    /*
     *给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素
     *B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。 
     */
     public static int[] multiply(int[] A) {
         int n = A.length;
         if (A == null || n == 0) {
                return new int[1];
            }
            int[] B = new int[n];
            int tmp1 = 1;
            int[] tmp2 = new int[n];
            tmp2[n - 1] = 1;
            //上三角
            for (int i = 1; i < n; i++) {
                tmp2[n - i - 1] = tmp2[n - i] * A[n - i];
            }
            for (int i = 0; i < n; i++) {
                if(i!=0){
                    //下三角
                    tmp1 *=A[i-1];
                }
                B[i] = tmp1 * tmp2[i];
            }
            return B;
     }
    
    /*
     * 数组的逆序对
     * 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,
     * 求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
     */
    public static int InversePairs(int [] array) {
        int n = array.length;
        int P = 0;
        for(int i = 0; i < n;i++){
            for(int j = i; j < n-1;j++){
                if(array[j] > array[j+1]) P++;
            }    
        }
        return P%1000000007;
    }
    
    /*
     * 统计一个数字在排序数组中出现的次数。
     */
    public static int GetNumberOfK(int [] array , int k) {
        int count = 0;
        int n = array.length;
        for (int i = 0; i< n ;i++){
            if(k == array[i]) count++;
        }
        return count;  
    }
    
    /*
     * 数组中出现一次的数
     * 一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。 
     * 分析:这俩数一定相异,异或为1.相同异或为0;相异异或为1,0和任何数异或是其本身。
     * 
     */
    public static void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        if(array.length < 2) return ;
       int myxor = 0;
       int flag = 1;
       for(int i = 0 ; i < array.length; ++ i )
           myxor ^= array[i];
       while((myxor & flag) == 0) flag <<= 1;
       for(int i = 0; i < array.length; ++ i ){
           if((flag & array[i]) == 0) num2[0]^= array[i];
           else num1[0]^= array[i];
       }
   }
    
    /*
     * 求一个数组中相同数字出现的次数/
     * 使用hashmap<key,value> ,使用迭代器 ,求value。
     */
    public static void FindNumsAppear(int [] array) {
        int n = array.length;
        Map<Integer, Integer> map = new HashMap<>();
       
        for (int i = 0; i < n ;i++){
            if (map.get(array[i])!= null){
                map.put(array[i],map.get(array[i]+1));    
            }else{
                map.put(array[i], 1);
            }
        }
        //获得所有的键
        Set<Integer> keyset = map.keySet();
        
        //迭代器
        Iterator<Integer> it = keyset.iterator();
        
        while(it.hasNext()){
            Integer key = it.next();
            Integer value = map.get(key);
        
            System.out.println(key+"值"+value+"次");
        }
    }
    /*
     * 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。
     * 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},
     * 那么对应的输出是第一个重复的数字2。
     */
     // Parameters:
    //    numbers:     an array of integers
    //    length:      the length of array numbers
    //    duplication: (Output) the duplicated number in the array number,length 
    //of duplication array is 1,so using duplication[0] = ? in implementation;
    //                  Here duplication like pointor in C/C++, duplication[0] 
    //equal *duplication in C/C++
    //    这里要特别注意~返回任意重复的一个,赋值duplication[0]
    // Return value:       true if the input is valid, and there are some
    //duplications in the array number
    //                     otherwise false
    public boolean duplicate(int numbers[],int length,int [] duplication) {
 
        StringBuffer sb = new StringBuffer(); 
        for(int i = 0; i < length; i++){
                sb.append(numbers[i] + "");
            }
        for(int j = 0; j < length; j++){
            //indexOf()方法从数组的开头(位置0)开始向后查找,lastIndexOf()方法则从数组的末尾开始向前查找。
            //当数组(字符串)中所要查询的数(字符串/字符)在字符串(数组)中只出现一次的时候 二者返回的索引值相同
            //当数组(字符串)中所要查询的数(字符串/字符)在字符串(数组)中出现两次及以上的时候  
            //indexOf  返回的是 valuesearch 第一次在数组(字符串)出现的位置(从左往右)
            //lastIndexOf 返回的是 valuesearch 最后一次在数组(字符串)出现的位置(从左往右)《只不过查询的方向不同而已》
            if(sb.indexOf(numbers[j]+"") != sb.lastIndexOf(numbers[j]+"")){
                duplication[0] = numbers[j];
                return true;
            }
        }
        return false;
        
    }

    /*
     * 丑数
     * 把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 
     * 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
     */
     public static int GetUglyNumber_Solution(int index) {
         //if (index == 0) return 0;
         if (index < 7) return index;
         
         int t2 = 0;
         int t3 = 0;
         int t5 = 0;
         int[] arr = new int[index];
         arr[0] =1;
         
         for (int i = 1; i < index ;i++){
             arr[i] = Math.min(arr[t2]*2, Math.min(arr[t3]*3, arr[t5]*5));
             if(arr[i] == arr[t2]*2) t2++;
             if(arr[i] == arr[t3]*3) t3++;
             if(arr[i] == arr[t5]*5) t5++;     
         }
         return arr[index-1];
     }
    
     /*
      *把数组排成最小的数
     * 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
     * 例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
     */
    public static String PrintMinNumber(int [] numbers) {
        int n;
        String s="";
        ArrayList<Integer> list=new ArrayList<Integer>();
        n=numbers.length;
             
        for(int i=0;i<n;i++){
            list.add(numbers[i]);//将数组放入arrayList中
        }
        //实现了Comparator接口的compare方法,将集合元素按照compare方法的规则进行排序
        Collections.sort(list,new Comparator<Integer>(){
         
            @Override
            public int compare(Integer str1, Integer str2) {
                // TODO Auto-generated method stub         
                    String s1=str1+""+str2;
                    String s2=str2+""+str1;
                     
                    return s1.compareTo(s2);
                }
            });
         
        for(int j:list){
            s+=j;
        }
        return s;
    }
    
    /*
     * 数字中出现1的次数
     * 1~13中包含1的数字有1、10、11、12、13因此共出现6次
     * 求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
     */
    public static int NumberOf1Between1AndN_Solution(int n) {
        int count=0;//1出现的次数
        while(n>0){
            String str = String.valueOf(n);  // 把数字变成字符串
            char[] chars = str.toCharArray(); //把字符串变成字符组
            for (int i = 0 ; i< chars.length ;i++){
                if (chars[i] == '1') count++;
            }    
            n--;
        }
        return count;
    }
    
    /*
     * 最大子序列
     * 例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,
     * 返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
     */
    public static int FindGreatestSumOfSubArray(int[] array) {
        //int n = array.length;
        List<Integer> sum = new ArrayList<>();
        for (int i = 0; i < array.length;i++){
            int sum1 = 0;
            for(int j = i; j < array.length; j++){
                sum1 += array[j];
                sum.add(sum1); 
            }          
        }
        
        if (sum.size() <= 0) return 0;
        Collections.sort(sum);
        return sum.get(sum.size()-1);
    }
    
    /*
     * 最小的k 个数
     * 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,
     */
    public static ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        int temp = 0;
        boolean isExchange;
        int n = input.length;
        ArrayList<Integer> lmin = new ArrayList<>();
        
        if (k <= n){
            for (int i = 1 ;i < n ;i++){
                isExchange = false;
                for (int j = 0 ;j < n-1 ;j++){
                    if (input[j] >= input[j+1]){
                    temp = input[j];
                    input[j] = input[j+1];
                    input[j+1] = temp;
                    isExchange = true;
                    }
                }
                if (isExchange == false) break;         
            }
            for(int i = 0; i < k ;i++){
                lmin.add(input[i]);
            }
            return lmin;
        }else{
            return lmin;
        } 
   }
    
    /*
     * 
     * 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,
     * 所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
     */
    public static void reOrderArray(int [] array) {
        ArrayList<Integer> odd = new ArrayList<>(); //奇数
        ArrayList<Integer> even = new ArrayList<>(); //偶数
        for (int i = 0; i< array.length ; i++){
            if (array[i]%2 == 1){
                odd.add(array[i]);
            }else{
                even.add(array[i]);
            }
        }
        int m = 0;
        for (int i = 0; i < odd.size(); i++){
            array[m] = odd.get(i);
            m++;
        }
        for (int i = 0; i < even.size(); i++){
            array[m] = even.get(i);
            m++;
        }
    }
    
    /*
     * 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方
     */
    public static double Power(double base, int exponent) {
        if(base == 0 && exponent != 0) return 0;
        if(base != 0 && exponent == 0) return 1;
        if(exponent == 1) return base;
        
        if(exponent < 0){
            base = 1/base;
            exponent = Math.abs(exponent);
        }
        
        double result = 1;
        int flag = 1;
        double result1 = 1;
        while (flag != 0){
            result1 *= base;
            
            if ((flag&exponent) != 0){
                result *= result1;
            }
            flag = flag << 1;
        }    
        return result;
  }
    
    
    /*
     * 顺时针打印数组
     */
    public static ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer>  list= new ArrayList<Integer>();
        
        
        int rows = matrix.length; //行数
        int colums = matrix[0].length; //列数
//        System.out.println("行"+rows+" 列"+colums);
        
//        for (int i = 0; i < rows ;i++){
//            for (int j = 0 ;j < colums ; j++){
//                System.out.print(matrix[i][j]+" ");
//            }
//            System.out.println();
//        }
        
        if (matrix == null || rows ==0 || colums == 0  ){
              return list;
        }
        
        int left = 0 ; 
        int right = colums - 1;  //列数
        int top = 0;
        int bottom = rows - 1;  //行数
        
        
        if (matrix[0].length == 1) {
            for (int i = 0; i < matrix.length; i++)
                list.add(matrix[i][0]);
                //System.out.print(matrix[i][0] + " ");
                return list;
        } else if (matrix.length == 1 && matrix[0].length != 1) {
            for (int i = 0; i < matrix[0].length; i++) 
                list.add(matrix[0][i]);
               // System.out.print(matrix[0][i] + " ");
                return list;
        } else if (matrix.length > 1) {
            while(left <= right && top <= bottom){
                //从左往右
                for(int i = left; i <= right ; ++i){
                       list.add(matrix[top][i]); //第一行不变,列在变
                   }
                //从上往下
         
                for(int j = top+1 ; j <= bottom ; ++j){
                    list.add(matrix[j][right]); // 最后一列不变,行变
                }
                //从右往左
                if(bottom != top ){
                    for (int i = right-1 ;i >= left ; --i)
                        list.add(matrix[bottom][i]); //最后一行不变,列在变
                }
                //从下往上
                if(right != left ){
                    for (int j = bottom -1 ; j > top ;--j)
                        list.add(matrix[j][left]);  //第一列不变,行在变
                }
                left++;right--;
                top++;bottom--;
            }
        }
        return list;
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值