日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

华为机试编程题学习

發布時間:2024/1/8 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 华为机试编程题学习 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

入門題(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(); //讀入數字int count = 0; //記錄轉換后的數字for(int i=0; i < s.length()-2; i++){//由于前面兩位是'0x',故從第三位開始char tc = s.charAt(i+2); int t = 0; //記錄字母轉換成的數值//將字母轉換為數值if(tc>='0' && tc<='9')t = tc - '0';//字母'A'/'a'~'F''f'對應數字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);//獲取個數int num = sc.nextInt();//創建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){// 不滿足題目給定坐標規則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");}}// 校驗是否有重復子串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();//統計每個字母的數量HashMap<Character, Integer> map = new HashMap<>();for (char aChar : chars) {map.put(aChar, (map.getOrDefault(aChar, 0) + 1));}//找到數量最少的字符數量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;//重載比較,按照區間首排序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;}}); //放入第一個區間res.add(intervals.get(0)); int count = 0;//遍歷后續區間,查看是否與末尾有重疊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++;//區間有重疊,更新結尾}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));} }


import java.util.*;public class Main {public static void main(String[] args){Scanner sc = new Scanner(System.in);HashMap<Integer,String> map = new HashMap<>();while(sc.hasNextLine()){// 學生成績數int n = Integer.parseInt(sc.nextLine());//1是升序,0是降序int flag = Integer.parseInt(sc.nextLine());// 每一行包括姓名編號,成績int[][] score = new int[n][2];for(int i=0;i<n;i++){String[] nameAndScore = sc.nextLine().split(" ");// 學生用編號代替score[i][0] = i;score[i][1] = Integer.parseInt(nameAndScore[1]);map.put(i,nameAndScore[0]);}// 自定義排序Arrays.sort(score,(o1,o2) ->{// 倒序,按第二列的成績降序排列,如果相等的話,返回0,順序不變,因為默認編號是升序的,符合題意if(flag==0){return o2[1] - o1[1];}else{// 按成績升序排序return o1[1] - o2[1];}});// 根據已經排序后的數組,順序輸出結果for(int i=0;i<n;i++){System.out.println(map.get(score[i][0]) + " " + score[i][1]);}}} }

import java.util.Stack;public class Solution {/*** * @param s string字符串 * @return bool布爾型*/public boolean isValid (String s) {// write code hereStack<Character> stack = new Stack<>();for(int i = 0; i < s.length(); i++){char c = s.charAt(i);if(c == '(' || c == '[' || c == '{')stack.push(c);else{if(stack.isEmpty())return false;char topChar = stack.pop();if(c == ')' && topChar != '(')return false;else if(c == ']' && topChar != '[')return false;else if(c == '}' && topChar != '{')return false;}}return stack.isEmpty();} }

class Solution {public int maxDepth(String s) {int depth = 0;int max = 0;for(int i = 0; i < s.length(); i++) {char c = s.charAt(i);if(c == '(') {depth++;max = Math.max(max, depth);}else if(c == ')'){depth--;}}return max;} }

class Solution {private List<List<Integer>> ans = new ArrayList<>();public List<List<Integer>> combine(int n, int k) {getCombine(n, k, 1, new ArrayList<>());return ans;}public void getCombine(int n, int k, int start, List<Integer> list) {if(k == 0) {ans.add(new ArrayList<>(list));return;}for(int i = start;i <= n - k + 1;i++) {list.add(i);getCombine(n, k - 1, i+1, list);list.remove(list.size() - 1);}} }

雙指針

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; ) {//如果剩余子串長度小于目前查找到的最長回文子串的長度,直接終止循環// (因為即使他是回文子串,也不是最長的,所以直接終止循環,不再判斷)if (n - i <= maxLen / 2)break;int left = i;int right = i;while (right < n - 1 && A.charAt(right + 1) == A.charAt(right))++right; //過濾掉重復的//下次在判斷的時候從重復的下一個字符開始判斷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<>();//存放所有可能的結果,不用擔心重復問題set.add(0);//不添加砝碼時候的重量int n = in.nextInt();//個數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();//砝碼個數}for(int i=0;i<n;i++){//遍歷砝碼ArrayList<Integer> list = new ArrayList<>(set);//取當前所有的結果for(int j=1;j<=nums[i];j++){//遍歷個數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); // 偶數層 -> 隊列頭部else tmp.addFirst(node.val); // 奇數層 -> 隊列尾部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){//標準輸入Scanner sc=new Scanner(System.in);while(sc.hasNext()){//輸入正偶數int n=sc.nextInt();//用于記錄輸入的n個整數int[] arr=new int[n];//用于存儲所有的奇數ArrayList<Integer> odds=new ArrayList<>();//用于存儲所有的偶數ArrayList<Integer> evens=new ArrayList<>();for(int i=0;i<n;i++){arr[i]=sc.nextInt();//將奇數添加到oddsif(arr[i]%2==1){odds.add(arr[i]);}//將偶數添加到evensif(arr[i]%2==0){evens.add(arr[i]);}}//下標對應已經匹配的偶數的下標,值對應這個偶數的伴侶int[] matcheven=new int[evens.size()];//記錄伴侶的對數int count=0;for(int j=0;j<odds.size();j++){//用于標記對應的偶數是否查找過boolean[] v=new boolean[evens.size()];//如果匹配上,則計數加1if(find(odds.get(j),matcheven,evens,v)){count++;}}System.out.println(count);} }//判斷奇數x能否找到伴侶private static boolean find(int x,int[] matcheven,ArrayList<Integer> evens,boolean[] v){for(int i=0;i<evens.size();i++){//該位置偶數沒被訪問過,并且能與x組成素數伴侶if(isPrime(x+evens.get(i))&&v[i]==false){v[i]=true;/*如果i位置偶數還沒有伴侶,則與x組成伴侶,如果已經有伴侶,并且這個伴侶能重新找到新伴侶,則把原來伴侶讓給別人,自己與x組成伴侶*/if(matcheven[i]==0||find(matcheven[i],matcheven,evens,v)){matcheven[i]=x;return true;}}}return false;}//判斷x是否是素數private static boolean isPrime(int x){if(x==1) return false;//如果能被2到根號x整除,則一定不是素數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++) {// 如果當前是素數if (isPrim[i]) {// 就把從 i*i 開始,i 的所有倍數都設置為 false。for (int j = i * i; j < n; j+=i) {isPrim[j] = false;}}}// 計數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整型一維數組 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++) {//窗口右移進入哈希表統計出現次數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;} }

總結

以上是生活随笔為你收集整理的华为机试编程题学习的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。