面试中的算法(持续更新中)

  • 给定一个数组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;
        }
  •  

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