华为机试编程题学习
入門題(5題)
(1)輸入處理(重要)
import java.util.Scanner; import java.lang.Math;public class Main{public static void main(String[] args){Scanner in = new Scanner(System.in);while(in.hasNextLine()){String s = in.nextLine(); //讀入數(shù)字int count = 0; //記錄轉(zhuǎn)換后的數(shù)字for(int i=0; i < s.length()-2; i++){//由于前面兩位是'0x',故從第三位開始char tc = s.charAt(i+2); int t = 0; //記錄字母轉(zhuǎn)換成的數(shù)值//將字母轉(zhuǎn)換為數(shù)值if(tc>='0' && tc<='9')t = tc - '0';//字母'A'/'a'~'F''f'對應(yīng)數(shù)字10~15else if(tc>='A' && tc<='F')t = tc - 'A' + 10;else if(tc>='a' && tc<='f')t = tc - 'a' +10;//計算加和count += t * Math.pow(16, s.length()-i-3);}System.out.println(count);}} } import java.util.Scanner; public class Main{public static void main(String[] args){Scanner in = new Scanner(System.in);while(in.hasNext()){String str = in.nextLine();String s1 = str.substring(2);int a = Integer.valueOf(s1,16);System.out.println(a);}} }(3)快速排序
import java.util.*;public class Test {public static void main(String[] args) {Scanner sc = new Scanner(System.in);//獲取個數(shù)int num = sc.nextInt();//創(chuàng)建TreeSet進行去重排序TreeSet set = new TreeSet();//輸入for(int i =0 ; i < num ;i++){set.add(sc.nextInt());}//輸出Iterator iterator = set.iterator();while (iterator.hasNext()){System.out.println(iterator.next());}} }(4)哈希表
import java.util.HashSet; import java.util.Scanner;public class Main {public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);String str=in.next();HashSet<Character> hs=new HashSet<Character>();for(int i=0;i<str.length();i++)hs.add(str.charAt(i));System.out.println(hs.size());}}(5)遞歸
public static int JumpFloor(int n) {return Fibonacci(n, 1, 1);}public static int Fibonacci(int n, int a, int b) {if (n <= 1)return b;return Fibonacci(n - 1, b, a + b);} public static int JumpFloor(int n) {return Fibonacci(n, 1, 1);}public static int Fibonacci(int n, int a, int b) {if (n <= 1)return b;return Fibonacci(n - 1, b, a + b);} class Solution { public:int jumpFloor(int number) {if (number <= 0) {return 0;}if (number == 1) {return 1;}if (number == 2) {return 2;}int first = 1, second = 2, third = 0;for (int i = 3; i <= number; i++) {third = first + second;first = second;second = third;}return third;} };字符串操作
import java.util.*; import java.io.*;public class Main{public static void main(String[] args) throws IOException {BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));String[] in = bf.readLine().split(";");int x = 0;int y = 0;for(String s : in){// 不滿足題目給定坐標(biāo)規(guī)則if(!s.matches("[WASD][0-9]{1,2}")){continue;}int val = Integer.valueOf(s.substring(1));switch(s.charAt(0)){case 'W':y += val;break;case 'S':y -= val;break;case 'A':x -= val;break;case 'D':x += val;break;}}System.out.println(x+","+y);} } import java.util.*; import java.util.regex.*; public class Main{public static void main(String[] arg){Scanner sc = new Scanner(System.in);while(sc.hasNext()){String str = sc.next();if(str.length() <= 8){System.out.println("NG");continue;}if(getMatch(str)){System.out.println("NG");continue;}if(getString(str, 0, 3)){System.out.println("NG");continue;}System.out.println("OK");}}// 校驗是否有重復(fù)子串private static boolean getString(String str, int l, int r) {if (r >= str.length()) {return false;}if (str.substring(r).contains(str.substring(l, r))) {return true;} else {return getString(str,l+1,r+1);}}// 檢查是否滿足正則private static boolean getMatch(String str){int count = 0;Pattern p1 = Pattern.compile("[A-Z]");if(p1.matcher(str).find()){count++;}Pattern p2 = Pattern.compile("[a-z]");if(p2.matcher(str).find()){count++;}Pattern p3 = Pattern.compile("[0-9]");if(p3.matcher(str).find()){count++;}Pattern p4 = Pattern.compile("[^a-zA-Z0-9]");if(p4.matcher(str).find()){count++;}if(count >= 3){return false;}else{return true;}} } import java.util.Collections; import java.util.HashMap; import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNext()) {String s = scanner.nextLine();char[] chars = s.toCharArray();//統(tǒng)計每個字母的數(shù)量HashMap<Character, Integer> map = new HashMap<>();for (char aChar : chars) {map.put(aChar, (map.getOrDefault(aChar, 0) + 1));}//找到數(shù)量最少的字符數(shù)量Collection<Integer> values = map.values();Integer min = Collections.min(values);//用空字符串替換該字母for (Character character : map.keySet()) {if (map.get(character) == min){s = s.replaceAll(String.valueOf(character), "");}}System.out.println(s);}} }import java.util.Scanner;
public class Main {public static void main(String[] args){Scanner sc = new Scanner(System.in);while(sc.hasNext()){String s = sc.next();if(s.contains(".")){System.out.println(ip2num(s));}else{System.out.println(num2ip(Long.parseLong(s)));}}}public static long ip2num(String ip){String[] iip = ip.split("\\.");Long ans = (long)0;for(int i = 0; i<4; i++){ans = ans * 256 + Long.parseLong(iip[i]);}return ans;}public static String num2ip(long num){String[] ans = new String[4];for(int i=3; i>=0; i--){ans[i] = Long.toString(num % 256);num = num / 256;}return String.join(".", ans);} } import java.util.*;public class Main{public static void main(String[] args){Scanner scan = new Scanner(System.in);String input = scan.nextLine();StringBuilder res = new StringBuilder(input);System.out.println(res.reverse());} }排序
public static void main(String[] args) {Scanner sc = new Scanner(System.in);while (sc.hasNext()){int next = sc.nextInt();TreeMap<Integer,Integer> map = new TreeMap<>();for (int i = 0; i < next; i++) {int key = sc.nextInt();int value = sc.nextInt();if (map.containsKey(key)){map.put(key,map.get(key)+value);}else {map.put(key,value);}}for (Map.Entry<Integer, Integer> integerIntegerEntry : map.entrySet()) {System.out.println(integerIntegerEntry.getKey()+" "+integerIntegerEntry.getValue());}} import java.util.*;public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);int n = in.nextInt();String[] array = new String[n];for (int i = 0; i < n; i++) {array[i] = in.next();}Arrays.sort(array);for (String str : array) {System.out.println(str);}} } import java.util.*; public class Solution {public ArrayList<Interval> merge(ArrayList<Interval> intervals) {ArrayList<Interval> res = new ArrayList<>();//去除特殊情況if(intervals.size() == 0) return res;//重載比較,按照區(qū)間首排序Collections.sort(intervals, new Comparator<Interval>(){public int compare(Interval o1, Interval o2){if(o1.start != o2.start)return o1.start - o2.start;elsereturn o1.end - o2.end;}}); //放入第一個區(qū)間res.add(intervals.get(0)); int count = 0;//遍歷后續(xù)區(qū)間,查看是否與末尾有重疊for(int i = 1; i < intervals.size(); i++){Interval o1 = intervals.get(i);Interval origin = res.get(count);if(o1.start > origin.end){res.add(o1);count++;//區(qū)間有重疊,更新結(jié)尾}else{ res.remove(count);Interval s = new Interval(origin.start, o1.end);if(o1.end < origin.end)s.end = origin.end;res.add(s);}}return res;} } import java.util.*;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNext()){String[] ss = scanner.nextLine().split(" ");Integer a = Integer.parseInt(ss[0]);String x = ss[ss.length-2];Integer k = Integer.parseInt(ss[ss.length-1]);List<String> list = new ArrayList<>();for (int i = 1; i <=a ; i++) {if (isBrother(x,ss[i])){list.add(ss[i]);}}int size = list.size();System.out.println(size);if (size>=k){Collections.sort(list);System.out.println(list.get(k-1));}}}public static boolean isBrother(String x,String y){if (x.length()!=y.length()||y.equals(x)){return false;}char[] s = x.toCharArray();char[] j= y.toCharArray();Arrays.sort(s);Arrays.sort(j);return new String(s).equals(new String(j));} }
雙指針
class Solution {public int findLengthOfLCIS(int[] nums) {if(nums.length <= 1)return nums.length;int ans = 1;int count = 1;for(int i=0;i<nums.length-1;i++) {if(nums[i+1] > nums[i]) {count++;} else { count = 1;}ans = count > ans ? count : ans;}return ans;} } class Solution {public int lengthOfLIS(int[] nums) {if(nums.length == 0) return 0;int[] dp = new int[nums.length];int res = 0;Arrays.fill(dp, 1);for(int i = 0; i < nums.length; i++) {for(int j = 0; j < i; j++) {if(nums[j] < nums[i]) dp[i] = Math.max(dp[i], dp[j] + 1);}res = Math.max(res, dp[i]);}return res;} } /*中心擴散法*/public int getLongestPalindrome(String A, int n) {//邊界條件判斷if (n < 2)return A.length();//maxLen表示最長回文串的長度int maxLen = 0;for (int i = 0; i < n; ) {//如果剩余子串長度小于目前查找到的最長回文子串的長度,直接終止循環(huán)// (因為即使他是回文子串,也不是最長的,所以直接終止循環(huán),不再判斷)if (n - i <= maxLen / 2)break;int left = i;int right = i;while (right < n - 1 && A.charAt(right + 1) == A.charAt(right))++right; //過濾掉重復(fù)的//下次在判斷的時候從重復(fù)的下一個字符開始判斷i = right + 1;//然后往兩邊判斷,找出回文子串的長度while (right < n - 1 && left > 0 && A.charAt(right + 1) == A.charAt(left - 1)) {++right;--left;}//保留最長的if (right - left + 1 > maxLen) {maxLen = right - left + 1;}}//截取回文子串return maxLen;} import java.util.*;public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);while (in.hasNextInt()) { // 注意 while 處理多個 caseHashSet<Integer> set = new HashSet<>();//存放所有可能的結(jié)果,不用擔(dān)心重復(fù)問題set.add(0);//不添加砝碼時候的重量int n = in.nextInt();//個數(shù)int[] w = new int[n];int[] nums = new int[n];for(int i=0;i<n;i++){w[i] = in.nextInt();//砝碼的重量}for(int i=0;i<n;i++){nums[i] = in.nextInt();//砝碼個數(shù)}for(int i=0;i<n;i++){//遍歷砝碼ArrayList<Integer> list = new ArrayList<>(set);//取當(dāng)前所有的結(jié)果for(int j=1;j<=nums[i];j++){//遍歷個數(shù)for(int k=0;k<list.size();k++){set.add(list.get(k) + w[i] * j);}}}System.out.println(set.size());}} } class Solution {public List<List<Integer>> levelOrder(TreeNode root) {Queue<TreeNode> queue = new LinkedList<>();List<List<Integer>> res = new ArrayList<>();if(root != null) queue.add(root);while(!queue.isEmpty()) {List<Integer> tmp = new ArrayList<>();for(int i = queue.size(); i > 0; i--) {TreeNode node = queue.poll();tmp.add(node.val);if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}res.add(tmp);}return res;} } class Solution {public List<List<Integer>> levelOrder(TreeNode root) {Queue<TreeNode> queue = new LinkedList<>();List<List<Integer>> res = new ArrayList<>();if(root != null) queue.add(root);while(!queue.isEmpty()) {LinkedList<Integer> tmp = new LinkedList<>();for(int i = queue.size(); i > 0; i--) {TreeNode node = queue.poll();if(res.size() % 2 == 0) tmp.addLast(node.val); // 偶數(shù)層 -> 隊列頭部else tmp.addFirst(node.val); // 奇數(shù)層 -> 隊列尾部if(node.left != null) queue.add(node.left);if(node.right != null) queue.add(node.right);}res.add(tmp);}return res;} }其他
import java.util.Scanner; import java.lang.Math;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int A = sc.nextInt();int B = sc.nextInt();for(int i = Math.min(A, B); i > 0; i--) {if(A % i == 0 && B % i == 0) {System.out.println(A*B/i);break;}}}} import java.util.Scanner; import java.util.ArrayList;public class Main{static int max=0;public static void main(String[] args){//標(biāo)準(zhǔn)輸入Scanner sc=new Scanner(System.in);while(sc.hasNext()){//輸入正偶數(shù)int n=sc.nextInt();//用于記錄輸入的n個整數(shù)int[] arr=new int[n];//用于存儲所有的奇數(shù)ArrayList<Integer> odds=new ArrayList<>();//用于存儲所有的偶數(shù)ArrayList<Integer> evens=new ArrayList<>();for(int i=0;i<n;i++){arr[i]=sc.nextInt();//將奇數(shù)添加到oddsif(arr[i]%2==1){odds.add(arr[i]);}//將偶數(shù)添加到evensif(arr[i]%2==0){evens.add(arr[i]);}}//下標(biāo)對應(yīng)已經(jīng)匹配的偶數(shù)的下標(biāo),值對應(yīng)這個偶數(shù)的伴侶int[] matcheven=new int[evens.size()];//記錄伴侶的對數(shù)int count=0;for(int j=0;j<odds.size();j++){//用于標(biāo)記對應(yīng)的偶數(shù)是否查找過boolean[] v=new boolean[evens.size()];//如果匹配上,則計數(shù)加1if(find(odds.get(j),matcheven,evens,v)){count++;}}System.out.println(count);} }//判斷奇數(shù)x能否找到伴侶private static boolean find(int x,int[] matcheven,ArrayList<Integer> evens,boolean[] v){for(int i=0;i<evens.size();i++){//該位置偶數(shù)沒被訪問過,并且能與x組成素數(shù)伴侶if(isPrime(x+evens.get(i))&&v[i]==false){v[i]=true;/*如果i位置偶數(shù)還沒有伴侶,則與x組成伴侶,如果已經(jīng)有伴侶,并且這個伴侶能重新找到新伴侶,則把原來伴侶讓給別人,自己與x組成伴侶*/if(matcheven[i]==0||find(matcheven[i],matcheven,evens,v)){matcheven[i]=x;return true;}}}return false;}//判斷x是否是素數(shù)private static boolean isPrime(int x){if(x==1) return false;//如果能被2到根號x整除,則一定不是素數(shù)for(int i=2;i<=(int)Math.sqrt(x);i++){if(x%i==0){return false;}}return true;} } class Solution {public int countPrimes(int n) {boolean[] isPrim = new boolean[n];Arrays.fill(isPrim, true);// 從 2 開始枚舉到 sqrt(n)。for (int i = 2; i * i < n; i++) {// 如果當(dāng)前是素數(shù)if (isPrim[i]) {// 就把從 i*i 開始,i 的所有倍數(shù)都設(shè)置為 false。for (int j = i * i; j < n; j+=i) {isPrim[j] = false;}}}// 計數(shù)int cnt = 0;for (int i = 2; i < n; i++) {if (isPrim[i]) {cnt++;}}return cnt;} } import java.util.*;public class Solution {/*** * @param arr int整型一維數(shù)組 the array* @return int整型*/public int maxLength (int[] arr) {// write code hereHashMap<Integer, Integer> map = new HashMap<>();int res = 0;for(int left = 0, right = 0; right < arr.length; right++) {//窗口右移進入哈希表統(tǒng)計出現(xiàn)次數(shù)if(map.containsKey(arr[right])) map.put(arr[right], map.get(arr[right]) + 1);else map.put(arr[right], 1);while(map.get(arr[right]) > 1) {map.put(arr[left], map.get(arr[left++]) - 1);}res = Math.max(res, right - left + 1);}return res;} }總結(jié)
- 上一篇: PID微分器与滤波器的爱恨情仇
- 下一篇: Cesium针对DEM和3Dtiles通