面試中的算法(持續更新中)

  • 給定一個數組a,長度爲n,求數組中所有兩個元素相加之和爲N的小標i和j

  • import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int N = sc.nextInt();
            int[] arr = new int[n];
            Map<Integer, Integer> map = new HashMap<>();
            for (int i=0;i<n;i++){
                arr[i] = sc.nextInt();
                map.put(arr[i],i);
            }
    
            for (int i=0;i<n;i++){
                int complement = N - arr[i];
                if (map.containsKey(complement)){
                    System.out.println(i+":"+map.get(complement));
                }
            }
        }
    }
  • 三個線程的名字分別爲0,1,2,每個線程輸出十次,按照012012012. . .的方式輸出

  • public class Main {
        //用來記錄前一個數的值
        int x=-1;
    
        public static void main(String[] args){
            Main m = new Main();
    
            new Thread(m.new RunnableA("0")).start();
            new Thread(m.new RunnableB("1")).start();
            new Thread(m.new RunnableC("2")).start();
        }
    
        class RunnableA implements Runnable{
            private String name;
    
            public RunnableA(String name) {
                this.name = name;
            }
    
            @Override
            public void run(){
                for(int i=0;i<10;i++){
                    synchronized (Main.class){
                        if(x == 1 || x == 0){
                            try {
                                Main.class.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            i--;
                            continue;
                        } else {
                            System.out.print(name);
                            x = 0;
                            Main.class.notifyAll();
                        }
                    }
                }
            }
        }
    
        class RunnableB implements Runnable{
            private String name;
    
            public RunnableB(String name){
                this.name = name;
            }
    
            @Override
            public void run(){
                for(int i=0;i<10;i++){
                    synchronized (Main.class){
                        if(x == 1 || x == 2){
                            try {
                                Main.class.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            i--;
                            continue;
                        } else {
                            System.out.print(name);
                            x = 1;
                            Main.class.notifyAll();
                        }
                    }
                }
            }
        }
    
        class RunnableC implements Runnable{
            private String name;
    
            public RunnableC(String name){
                this.name = name;
            }
    
            @Override
            public void run(){
                for(int i=0;i<10;i++){
                    synchronized (Main.class){
                        if(x == 0 || x == 2){
                            try {
                                Main.class.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            i--;
                            continue;
                        } else {
                            System.out.print(name);
                            x = 2;
                            Main.class.notifyAll();
                        }
                    }
                }
            }
    
        }
    }
  • 給定一個字符串,得到這個數組按順序最小的字符串輸出,最小的輸出個數爲s

  • 例如:str=1584632   s=3   輸出:132
  • public class Main {
        public static void main(String[] args) {
            Scanner sc1 = new Scanner(System.in);
            Scanner sc2 = new Scanner(System.in);
    
            //輸入一個字符串
            String str = sc1.nextLine();
            //得到剩餘的最小的個數
            int s = sc2.nextInt();
    
            //將字符串變成 int[]
            int[] arr = new int[str.length()];
            for (int i=0;i<arr.length;i++){
                arr[i] = Integer.parseInt(str.substring(i,i+1));
            }
    
            //將值以及對應的下標存入HashMap中,並將值存入list列表中
            HashMap<Integer,Integer> map = new HashMap<>();
            List<Integer> list = new ArrayList<>();
            for (int i=0;i<arr.length;i++){
                map.put(arr[i],i);
                list.add(arr[i]);
            }
    
            //給列表進行排序
            Collections.sort(list);
            //將最小的 s 個整型存入HashMap中
            Map<Integer,Integer> map1 = new HashMap<>();
            for (int i=0;i<s;i++){
                map1.put(list.get(i),map.get(list.get(i)));
            }
    
            //對這個HashMap進行排序,按照 value 從小到大進行排序
            List<Map.Entry<Integer,Integer>> list1 = new ArrayList<>();
            Set<Map.Entry<Integer, Integer>> entries = map1.entrySet();
            for (Map.Entry<Integer,Integer> e : entries){
                list1.add(e);
            }
            Collections.sort(list1, new Comparator<Map.Entry<Integer, Integer>>() {
                @Override
                public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                    return o1.getValue() - o2.getValue();
                }
            });
    
            //排序完成後進行輸出,如果首位爲 0 那麼跳過
            for (Map.Entry<Integer,Integer> m : list1){
                if (m.getKey() != 0){
                    System.out.print(m.getKey());
                }
            }
        }
    }
  • 比較版本號:第二個版本號大於第一個那麼就返回true,否則返回false

  • import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
    
            for (int q = 0;q<n;q++){
                //記得轉義,並且next()方法遇到空格就會結束,而nextLine()不會
                //比如: 你好 你好
                /**
                 * 記得轉義,並且next()方法遇到空格就會結束,而nextLine()不會
                 * 比如: 你好 你好
                 *      nextLine()讀取到: 你好 你好
                 *      next()讀取到: 你好
                 */
                String[] str1 = sc.next().split("\\.");
                String[] str2 = sc.next().split("\\.");
                int maxIndex = Math.max(str1.length,str2.length);
                int[] arr1 = new int[maxIndex];
                int[] arr2 = new int[maxIndex];
                for (int i=0;i<str1.length;i++){
                    //字符串變整數
                    arr1[i] = Integer.valueOf(str1[i]);
                }
                for (int i=0;i<str2.length;i++){
                    arr2[i] = Integer.valueOf(str2[i]);
                }
    
                for (int i=0;i<=maxIndex;i++){
                    //兩個字符串一樣長並且都相等
                    if (i==maxIndex){
                        System.out.println("false");
                        break;
                    } else {
                        if (arr1[i]<arr2[i]){
                            System.out.println("true");
                            break;
                        } else if (arr1[i]>arr2[i]){
                            System.out.println("false");
                            break;
                        }
                    }
                }
            }
        }
    }
  • 一個數的各個位的平方和得到一個數,如果得到的結果爲1,則返回true,否則繼續這行這個操作

  • 例如:19
  • 1^2+9^2=82
  • 8^2+2^2=68
  • 6^2+8^2=100
  • 1^2+0^2+0^2=1
  • 則返回true
  • import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            for (int i = 0; i < n; i++) {
                int t = sc.nextInt();
                slove(t);
            }
            sc.close();
        }
    
        public static void slove(int t){
    
            Map<Integer,String> map = new HashMap<>();
            map.put(t," ");
            int num = 0;
            int k = 0;
            while (t!=1){
                char[] arr = String.valueOf(t).toCharArray();
                num = 0;
                for (int j = 0; j < arr.length; j++) {
                    k = arr[j] - '0';
                    num+=k*k;
                }
                t = num;
                //如果存在當前key那麼就不會得到1,輸出false
                if(map.get(t)!=null){
                    System.out.println("false");
                    return;
                }else {
                    map.put(t," ");
                }
            }
            System.out.println("true");
        }
    }
    
  • 數字和字符串進行歸併,每四個數字後邊跟一個字母,如果字母多餘那麼跟在後邊
  • import java.util.*;
    
    public class text {
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            String s1 = scanner.nextLine();
            String s2 = scanner.nextLine();
            String[] split1 = s1.split(" ");
            String[] split2 = s2.split(" ");
            if (split1.length == 0 && split2.length == 0) {
                System.out.println();
                return;
            }
            if (split1.length==0){
                System.out.println(s2);
                return;
            }
            if (split2.length==0){
                System.out.println(s1);
                return;
            }
    
            StringBuffer sb = new StringBuffer();
            int index = 0;
            for (int i=0;i<split1.length;i++){
                if (i%4 == 3 && index < split2.length){
                    sb.append(split1[i]).append(" ").append(split2[index++]).append(" ");
                } else {
                    sb.append(split1[i]).append(" ");
                }
            }
            //成立說明含有字母的序列沒有輸出完
            if (index <= split2.length-1){
                for (int i=index;i<split2.length;i++){
                    sb.append(split2[i]).append(" ");
                }
            }
            System.out.println(sb.toString().trim());
        }
    }
  • import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String s = sc.nextLine();
            //\\s表示   空格,回車,換行等空白符,
            //+號表示一個或多個的意思
            String[] str = s.split(",\\s+");
            Map<Integer, Integer> map = new HashMap<>();
            int sum = 0;
            for (int i = 0; i < str.length; i++) {
                int value = Integer.valueOf(str[i]);
                if (map.containsKey(-value) && map.get(-value) > 0) {
                    int count = map.get(-value);
                    map.put(-value, count - 1);
                    sum++;
                } else {
                    int count = map.getOrDefault(value, 0);
                    map.put(value, count + 1);
                }
            }
            System.out.println(sum);
         }
    }
    
  • 實現一個數組的最長遞增序列
  • import java.util.*;
    
    public class text5 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String[] str= sc.nextLine().split(" ");
            int[] arr = new int[str.length];
            for (int i = 0; i < str.length; i++){
                arr[i] = Integer.parseInt(str[i]);
            }
            int max = 0, count = 0, ss = 0, x = 0, y = 0;
            for (int i = 0; i < str.length - 1; i++) {
                y = i + 1;//判斷是否遞增,是的話count++;
                if (arr[i + 1] > arr[i]) {
                    count++;
                    if (count > max) {
                        max = count;
                        ss = x;
                    }
                } else {
                    count = 0;
                    x = y;//不連續遞增,則索引改變爲下一個目標
                }
            }
            for (int i = ss; i <= ss + max; i++) {
                if (i == (ss + max)) {
                    System.out.print(arr[i]);
                } else {
                    System.out.print(arr[i] + " ");
                }
            }
        }
    }
    
  • 歸併排序
  • 
    import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int[] a = new int[n];
            for (int i=0;i<n;i++){
                a[i] = sc.nextInt();
            }
            int[] sort = sort(a, 0, n - 1);
            for (int i=0;i<n;i++){
                System.out.println(sort[i] + " ");
            }
        }
    
        public static int[] sort(int[] a,int low,int high){
            int mid = (low + high) / 2;
            if(low < high){
                sort(a,low,mid);
                sort(a,mid+1,high);
                //左右歸併
                merge(a,low,mid,high);
            }
            return a;
        }
    
        public static void merge(int[] a, int low, int mid, int high) {
            int[] temp = new int[high-low+1];
            int i= low;
            int j = mid+1;
            int k=0;
            // 把較小的數先移到新數組中
            while(i<=mid && j<=high){
                if(a[i]<a[j]){
                    temp[k++] = a[i++];
                }else{
                    temp[k++] = a[j++];
                }
            }
            // 把左邊剩餘的數移入數組
            while(i<=mid){
                temp[k++] = a[i++];
            }
            // 把右邊邊剩餘的數移入數組
            while(j<=high){
                temp[k++] = a[j++];
            }
            // 把新數組中的數覆蓋nums數組
            for(int x=0;x<temp.length;x++){
                a[x+low] = temp[x];
            }
        }
    }
  • 分餅乾問題:沒個人要達到滿意,每個人至少分得一個餅乾
  • import java.util.*;
    
    public class Main {
        public static void main(String [] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int[] arr = new int[n];
            for (int i=0;i<n;i++){
                arr[i] = sc.nextInt();
            }
    
            System.out.println(outCookie(arr));
        }
    
        public static int outCookie(int[] arr) {
            if(arr.length <= 0) {
                return 0;
            }
            int[] sum = new int[arr.length];
            sum[0] = 1;
            for(int i = 1;i<sum.length;i++){
                sum[i] = 1;
                if(arr[i] > arr[i-1]){
                    sum[i] = sum[i-1]+1;
                }
            }
            for(int i = sum.length-2;i>=0;i--){
                if(arr[i] > arr[i+1]){
                    sum[i] = Math.max(sum[i],sum[i+1]+1);
                }
            }
            int num = 0;
            for(int i = 0;i < arr.length;i++){
                num += sum[i];
            }
            return num;
        }
    }
    
  • 使用兩個棧,使得輸出的棧有序
  • public static Stack<Integer> sortBy2Stack(Stack<Integer> stack){
            Stack<Integer> tempStack=new Stack();//結果棧
            int j=0;
            while(stack.size()>0){
                //pop:刪除此堆棧頂部的對象,並將該對象作爲此函數的值返回
                int temp=stack.pop();
                if(tempStack.size()!=0){//判斷結果棧是否爲空
                    //peek:查看此堆棧頂部的對象,而不從堆棧中刪除它
                    while (tempStack.size()>0 && tempStack.peek() > temp){
                        //push:將項目推送到此堆棧的頂部
                        stack.push(tempStack.pop());
                        j++;//記錄出棧次數
                    }
                    //push:將項目推送到此堆棧的頂部
                    tempStack.push(temp);
                    while(j>0){
                        //push:將項目推送到此堆棧的頂部
                        tempStack.push(stack.pop());
                        j--;//根據出棧次數重新壓棧
                    }
                }else{
                    tempStack.push(temp);
                }
            }
            return tempStack;
        }
  •  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章