Buckle exercise 1 (10 questions)

1. Given an integer array nums and an integer target value target, please find the two integers in the array whose sum is the target value target, and return their array indices.

You can assume that there will only be one answer for each input. However, the same element in the array cannot be repeated in the answer.

You can return answers in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

class Solution {
    public int[] twoSum(int[] nums, int target) {

    int [] result=new int[2];

            for(int i=0;i<=nums.length;i++){

                for(int j=i+1;j<=nums.length-1;j++){


                    int sum=nums[j]+nums[i];
                    if(sum==target){
                     result[0]=i;
                     result[1]=j;
                    }


                }

            }



            return result;
}




}

2. Given a 32-bit signed integer x, return the result of inverting the digit part of x.

Returns 0 if the inverted integer exceeds the range [−231, 231 − 1] for 32-bit signed integers.

Suppose the environment does not allow storage of 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321
Example 2:

Input: x = -123
Output: -321
Example 3:

Input: x = 120
Output: 21
Example 4:

Input: x = 0
Output: 0
 

hint:

-231 <= x <= 231 - 1

 public static int reverse(int x) {


            try {

                boolean b = true;
                if (x < 0) {
                    x = x * (-1);
                    b = false;
                }
                String num = String.valueOf(x);
                String num2 = "";
                for (int i = num.length() - 1; i >= 0; i--) {

                    if (num.charAt(i) != 'a') {
                        num2 += num.charAt(i);
                    }
                }

                if (b) {
                    return Integer.parseInt(num2);
                } else {
                    return -Integer.parseInt(num2);
                }


            } catch (Exception e) {
                return 0;
            }
        }

3. You and your friend, two people play Nim game together:

There is a pile of stones on the table.
You take turns taking your turns, with you as the first mover.
Each turn, the person taking their turn removes 1-3 stones.
Whoever takes the last stone is the winner.
Assume that each of your steps is an optimal solution. Write a function that determines if you can win the game given n number of stones. Returns true if it is possible to win; otherwise, returns false.

Example 1:

Input: n = 4
Output: false 
Explanation: If there are 4 stones in the pile, then you will never win the game;
     because whether you take 1, 2 or 3 stones, the last stone will always be yours friends take it.
Example 2:

Input: n=1
Output: true
Example 3:

Input: n=2
Output: true
 

hint:

1 <= n <= 231 - 1

 public boolean canWinNim(int n) {

        try {
        if(1<=n&&n<=3){
            return true;
        }
        else {
            if(n%4==0){
                return false;
            }
            return true;
        }
        }catch (Exception e){
            return false;

        }

    }

4. Number of palindromes

Given an integer x, return true if x is a palindrome; otherwise, return false.

A palindrome is an integer that reads the same in positive order (from left to right) and in reverse order (from right to left). For example, 121 is a palindrome, but 123 is not.

Example 1:

Input: x = 121
Output: true
Example 2:

Input: x = -121
Output: false
Explanation: Read from left to right, it is -121. Reading from right to left, it is 121-. Therefore it is not a palindrome.
Example 3:

Input: x = 10
Output: false
Explanation: Read from right to left, 01. Therefore it is not a palindrome.
Example 4:

Input: x=-101
Output: false

hint:

-231 <= x <= 231 - 1

class Solution {
    public boolean isPalindrome(int x) {

        
  try {
      if (x < 0) {
          return false;
      } else {
          String num = String.valueOf(x);
          String num2 = "";
          for (int i = num.length() - 1; i >= 0; i--) {

              if (num.charAt(i) != 'a') {
                  num2 += num.charAt(i);
              }
          }
        
          if (Integer.parseInt(num2) == x) {
              return true;
          } 
              return false;
          
      }
    }catch (Exception e){
      return false;
  }

    }
}

5. Add two numbers

You are given two non-empty linked lists representing two non-negative integers. They are stored in reverse order per digit, and each node can only store one digit.

Please add two numbers and return a linked list representing the sum in the same form.

You can assume that neither number starts with 0 except for the number 0.

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
 

hint:

The number of nodes in each linked list is in the range [1, 100]
0 <= Node.val <= 9
The title data ensures that the number represented by the list does not contain leading zeros

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        
     
        List<Integer> listNodes1=new ArrayList<>();
        while (true){
            listNodes1.add(l1.val);
            if (l1.next==null){
                break;
            }
            l1=l1.next;

        }

        List<Integer> listNodes2=new ArrayList<>();
        while (true){
            listNodes2.add(l2.val);
            if (l2.next==null){
                break;
            }
            l2=l2.next;
        }
        String num1="";
        String num2="";
        int num=0;
        int redis=0;
        int redis2=0;

        SingleLinkedList singleLinkedList=new SingleLinkedList();
        ListNode listNode=null;
        ListNode listNode2=null;
        List<Integer> maxList=new ArrayList<>();
        int max=0;
        int min=0;
       // System.out.println("listNodes1.size()="+listNodes1.size());
        //System.out.println("listNodes2.size()="+listNodes2.size());
        if(listNodes1.size()>listNodes2.size()){
            max=listNodes1.size();
            min=listNodes2.size();
            maxList= listNodes1;
        }
        else {
            max=listNodes2.size();
            min=listNodes1.size();
            maxList=  listNodes2;
        }
        System.out.println("max="+max);
        System.out.println("min="+min);

        for (int i=0;i<max;i++){

             if(i<min){
                num=listNodes2.get(i)+listNodes1.get(i)+redis2;
                if (num>10){
                    redis=num%10;
                    redis2=1;
                   listNode2=new ListNode(redis);


                }
               else if (num==10){
                    redis=0;
                    redis2=1;
                   listNode2=new ListNode(redis);

                }
               else {
                    listNode2=new ListNode(num);
                    redis2=0;
                }

                listNode=singleLinkedList.add(listNode2);
            }
            if(i>=min) {

                 num=maxList.get(i)+redis2;
                 if (num>10){
                     redis=num%10;
                     redis2=1;
                     listNode2=new ListNode(redis);


                 }
                 else if (num==10){
                     redis=0;
                     redis2=1;
                //     System.out.println("000");
                     listNode2=new ListNode(redis);

                 }
                 else {
                     listNode2=new ListNode(num);
                     redis2=0;
                 }
                listNode=singleLinkedList.add(listNode2);
             }
        }
        if(redis2>0){
            listNode2=new ListNode(redis2);
            listNode=singleLinkedList.add(listNode2);
        }




        return listNode;

    }
}
class SingleLinkedList {
        //先初始化一个头节点,头节点不用动
     ListNode head = new ListNode(0);

        public ListNode add(ListNode listNode) {
           ListNode temp=head;

            //遍历链表,找到最后
            while (true){
                //找到链表最后
                if(temp.next==null){
                    break;
                }
                //如果没有找到最后,将temp后移

                temp=temp.next;
            }
            //当退出while循环时,temp就指向了链表的最后
            //将最后节点的next,指向新的节点
            temp.next=listNode;

            return head.next;
        }
    }

6. Roman numerals to integers

Roman numerals contain the following seven characters: I, V, X, L, C, D and M.

Character Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, the Roman numeral 2 is written as II , which is two parallel 1s. 12 is written as XII , which is X + II . 27 is written as XXVII, which is XX + V + II.

Typically, smaller numbers in Roman numerals are to the right of larger numbers. But there are exceptions, for example, 4 is not written as IIII, but as IV. The number 1 is to the left of the number 5, and the number represented is equal to the number 4 obtained by subtracting the number 1 from the large number 5. Likewise, the number 9 is represented as IX. This particular rule only applies to the following six cases:

I can be placed to the left of V (5) and X (10) to represent 4 and 9.
X can be placed to the left of L (50) and C (100) to represent 40 and 90. 
C can be placed to the left of D (500) and M (1000) to represent 400 and 900.
Given a Roman numeral, convert it to an integer. Make sure the input is in the range 1 to 3999

Example 1:

Input: "III"
Output: 3
Example 2:

Input: "IV"
Output: 4
Example 3:

Input: "IX"
Output: 9
Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4.

hint:

1 <= s.length <= 15
s contains only characters ('I', 'V', 'X', 'L', 'C', 'D', 'M')
The item data guarantees that s is a valid Roman numerals, and indicate that the integer is in the range [1, 3999].
The test cases given in the question are all in accordance with the Roman numeral writing rules, and there will be no cross-digit situation.
Examples such as IL and IM do not meet the title requirements, 49 should be written as XLIX, and 999 should be written as CMXCIX.
For detailed writing rules of Roman numerals, please refer to Roman numerals - Mathematics .
Passed 463,234 Submitted 732,562

class Solution {
    public int romanToInt(String s) {

  int values[] ={1,4,5,9,10,40,50,90,100,400,500,900,1000};
        String roman[]={"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
       int Roman=0;
     
          for(int i=0;i<s.length();i++){

              for(int j=12;j>=0;j--) {
                  if (i + 1 < s.length() && (String.valueOf(s.charAt(i)) + String.valueOf(s.charAt(i+1))).equals(roman[j])){

                      Roman+=values[j];
                      i++;
                      break;
                  }
                  else {
                      if (String.valueOf(s.charAt(i)).equals(roman[j])) {
                          Roman += values[j];

                      }
                  }


              }


          }


        return Roman;


    }
}

7. Integer to Roman Numeral

Roman numerals contain the following seven characters: I, V, X, L, C, D, and M.

Character Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, the Roman numeral 2 is written as II , which is two parallel 1s. 12 is written as XII , which is X + II . 27 is written as XXVII, which is XX + V + II.

Typically, smaller numbers in Roman numerals are to the right of larger numbers. But there are exceptions, for example, 4 is not written as IIII, but as IV. The number 1 is to the left of the number 5, and the number represented is equal to the number 4 obtained by subtracting the number 1 from the large number 5. Likewise, the number 9 is represented as IX. This particular rule only applies to the following six cases:

I can be placed to the left of V (5) and X (10) to represent 4 and 9.
X can be placed to the left of L (50) and C (100) to represent 40 and 90. 
C can be placed to the left of D (500) and M (1000) to represent 400 and 900.
Given an integer, convert it to Roman numerals.

Example 1:

Input: num = 3
Output: "III"
Example 2:

Input: num = 4
Output: "IV"
Example 3:

Input: num = 9
Output: "IX"
Example 4:

Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Example 5:

Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90, IV = 4.
 

hint:

1 <= num <= 3999

class Solution {
    public String intToRoman(int num) {
 int values[] ={1,4,5,9,10,40,50,90,100,400,500,900,1000};
      String roman[]={"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
        int i=12;
        String Roman="";
        while (num>0){

           if(num>=values[i]){
                num=num-values[i];
                Roman+=roman[i];

            }
           else {
               i--;
           }

        }



        return Roman;

    }
}

8. Valid parentheses

Given a string s containing only '(', ')', '{', '}', '[', ']', determine whether the string is valid.

A valid string must satisfy:

Opening parentheses must be closed with closing parentheses of the same type.
Left parentheses must be closed in the correct order.
 

Example 1:

Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false
Example 4:

Input: s = "([)]"
Output: false
Example 5:

Input: s = "{[]}"
Output: true
 

hint:

1 <= s.length <= 104
s consists only of brackets '()[]{}'

class Solution {
    public boolean isValid(String s) {
  int length = s.length() / 2;
        for (int i = 0; i < length; i++) {
            s = s.replace("()", "").replace("{}", "").replace("[]", "");
        }
        System.out.println(s);

        return s.length() == 0;
    }
}

9. Longest Common Prefix

Write a function to find the longest common prefix in an array of strings.

Returns an empty string if no common prefix exists  "".

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: strs = ["dog", "racecar", "car"]
Output: ""
Explanation: The input does not have a common prefix.
 

hint:

1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of lowercase English letters only

class Solution { 

    public String longestCommonPrefix(String[] strs) {

     
        String s="";
        String s2="";
        int num[]=new int[strs.length];
        for(int i=0;i<strs.length;i++){
            num[i]=strs[i].length();
        }
        for (int gap = num.length / 2; gap > 0; gap /= 2) {
            // 从第gap个元素,逐个对其所在的组进行直接插入排序
            for (int i = gap; i < num.length ; i++) {
                int j = i;
                int temp = num[j];
                if (num[j] < num[j - gap]) {
                    while (j - gap >= 0 && temp < num[j - gap]) {
                        //移动
                        num[j] = num[j-gap];
                        j -= gap;
                    }
                    //当退出while后,就给temp找到插入的位置
                    num[j] = temp;
                }

            }
        }

        boolean b=false;
        int sum=0;
        String snum="";
        if(strs.length>1) {
            for (int k = 0; k < num[0]; k++) {

                for (int p = 1; p < strs.length; p++) {
                    if (String.valueOf(strs[0].charAt(k)).equals(String.valueOf(strs[p].charAt(k)))) {
                        b = true;
                        sum++;
                    } else {
                        b = false;
                        sum--;
                          break;
                    }
                }
                if (k == 0) {
                    if (!b) {
                        return "";
                    }
                }
                if(k>0){
                    if (!b) {
                         break;
                    }
                }
                if (b) {
                    snum += String.valueOf(strs[0].charAt(k));
                }
            }
        }
        else {
            snum=strs[0];
        }
      return snum;

    }
}

10. Merge two sorted linked lists

 Merge two ascending linked lists into a new  ascending  linked list and return. The new linked list is formed by splicing all the nodes of the given two linked lists.


Example 2:

Input: l1 = [], l2 = []
Output: []
Example 3:

Input: l1 = [], l2 = [0]
Output: [0]
 

hint:

The number of nodes in the two linked lists ranges from [0, 50]
-100 <= Node.val <= 100
l1 and l2 are in non-decreasing order

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  if(l1!=null||l2!=null) {

             List<Integer> list = new ArrayList<>();
             while (true) {
                 if (l1 != null) {
                     list.add(l1.val);
                     if (l1.next == null) {
                         break;
                     }
                     l1 = l1.next;
                 }
                 else {
                     break;
                 }
             }
             while (true) {
                 if (l2 != null) {
                     list.add(l2.val);
                     if (l2.next == null) {
                         break;
                     }
                     l2 = l2.next;
                 }
                 else {
                     break;
                 }
             }


             int temp = 0;
             for (int i = 0; i < list.size() - 1; i++) {

                 for (int j = 0; j < list.size() - 1 - i; j++) {
                     // 如果前面的数比后面的数大,则交换
                     if (list.get(j) < list.get(j + 1)) {

                         temp = list.get(j);
                         list.set(j, list.get(j + 1));
                         list.set(j + 1, temp);
                     }
                 }
             }
             //  list.forEach(System.out::println);
             ListNode listNode[] = new ListNode[list.size()];
             if (list != null) {

                 for (int i = 0; i < list.size(); i++) {
                     if (i == 0) {
                         listNode[i] = new ListNode(list.get(i));
                     } else {
                         listNode[i] = new ListNode(list.get(i), listNode[i - 1]);
                     }

                 }
             }
             return listNode[list.size() - 1];
         }
         else {

             return null;
         }
    }
}

Guess you like

Origin blog.csdn.net/qq_44716544/article/details/120358065