leetCode解题思路(easy篇)

1. Two Sum

题目要求:给定一个Integer nums数组 和一个 int target 返回数组中两数之和等于target的元素的下标。

解题思路:

1.枚举 两层for循环 On2

2.先排序 额外占用n空间存储nums副本,两个ij哨兵从排序后的数组两端搜索直到找到符合的值,之后确定值在远数组中的下标

public int[] twoSum(int[] nums, int target) {
        int[] nums2 = nums.clone();
        Arrays.sort(nums);
        int i = 0;
        int j = nums.length - 1;
        for (; i < j; ) {
            while (nums[i] + nums[j] > target) {
                j--;
            }
            while (nums[i] + nums[j] < target) {
                i++;
            }
            if (nums[i] + nums[j] == target) {
                break;
            }
        }
        for (int k = 0; k < nums2.length; k++) {
            if (nums2[k] == nums[i]) {
                i = k;
                break;
            }
        }
        for (int k = nums2.length - 1; k >= 0; k--) {
            if (nums2[k] == nums[j]) {
                j = k;
                break;
            }
        }
        return i < j ? new int[]{i, j} : new int[]{j, i};
    }

3.On方案,一个Map<index,value>存储已扫描过的数组中下标和值的对应关系

public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int temp = target - nums[i];
            if (map.containsKey(temp)) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);

        }
        return new int[2];
    }

7.Reverse Integer 

题目要求:给定integer串,返回反转后的integer

解题思路:

1.interger转成String 直接reverse后再转成integer(需要注意处理符号和处理溢出的integer)

2.循环/10 %10手动构造结果

public int reverse(int x) {
        long y = 0;
        while (x != 0) {
            y = y * 10 + x % 10;
            x /= 10;
        }
        if (y > Integer.MAX_VALUE || y < Integer.MIN_VALUE) {
            return 0;
        }
        return (int) y;
    }

9. Palindrome Number

题目要求:给定Integer判断是否是回文数

解题思路:与第七题类似,反转输入的数后判断两数是否相等。

14.Longest Common Prefix

题目要求:给定一组String[],取所有值的最长公共前缀

解题思路:贪心思想,认为当前解就是最优解,如果不符合要求则降低当前解的标准直到结束

public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        String best = strs[0];
        int length = strs[0].length();
        for (int i = 1; i < strs.length; i++) {
            while (length > 0 && !strs[i].startsWith(best.substring(0, length))) {
                length--;
            }
            if (length == 0) {
                break;
            }
        }
        return best.substring(0,length);
    }

20. Valid Parentheses

题目要求:给定一组大小中括号组成的String,判断括号是否成对出现且符合括号的开关要求

解题思路:就是一个简单的词法检查器,用栈实现,栈可以自己用数组构造,也可以用Stack<>

public boolean isValid(String s) {
        Set<Character> set = new HashSet<>();
        set.add('(');
        set.add('[');
        set.add('{');
        Map<Character, Character> map = new HashMap<>();
        map.put('(',')');
        map.put('[',']');
        map.put('{','}');
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (set.contains(s.charAt(i))) {
                stack.push(s.charAt(i));
            } else {
                if (stack.isEmpty() || map.get(stack.pop()) != s.charAt(i)) {
                    return false;
                }
            }
        }
        return stack.isEmpty() ? true : false;
    }

21. Merge Two Sorted Lists

 题目要求:按照大小顺序合并两个有序链表

解题思路:

1.OM+N的依次归并

 public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode start;
        ListNode res;
        ListNode i;
        ListNode j;
        if (l1.val > l2.val) {
            res = l2;
            i = l1;
            j = l2.next;
        } else {
            res = l1;
            i = l1.next;
            j = l2;
        }
        start = res;
        while (i != null && j !=null) {
            if (i.val < j.val) {
                res.next = i;
                i = i.next;
                res = res.next;
            } else {
                res.next = j;
                j = j.next;
                res = res.next;
            }
        }
        if (i != null) {
            res.next = i;
        } else {
            res.next = j;
        }
        return start;
    }

2.递归

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1,l2.next);
            return l2;
        }
    }

26. Remove Duplicates from Sorted Array

题目要求:有序数组去重

解题思路:扫一遍数组,可以额外占用N空间存储不重复的值,也可以在扫描的过程中直接把不重复的值覆盖到原来数组上边。

public int removeDuplicates(int[] nums) {
        if (null == nums || nums.length == 0) {
            return 0;
        }
        int index = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[i - 1]) {
                nums[++index] = nums[i];
            }
        }
        return ++index;
    }

27.Remove Element

题目要求:有序数组去重

解题思路:与26题类似,两个指针,扫一遍数组。

    public int removeElement(int[] nums, int val) {
        if (null == nums || nums.length == 0) {
            return 0;
        }
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[index++] = nums[i];
            }
        }
        return index;
    }

28. Implement strStr()

题目要求:实现String.indexOf()

解题思路:去jdk里看下实现就行

    public int strStr(String haystack, String needle) {
//        return haystack.indexOf(needle);
        if (haystack == null || needle == null || haystack.length() < needle.length()) {
            return -1;
        }

        char[] chars = haystack.toCharArray();
        char[] target = needle.toCharArray();
        for (int i = 0 ; i <= chars.length - needle.length(); i++){
            int j = 0;
            int k = i;
            for(; j < target.length; j++) {
                if (chars[k++] != target[j]) {
                    break;
                }
            }
            if (j == target.length) {
                return i;
            }
        }

        return -1;
    }

38. Count and Say

题目要求:给定n和表达规则,描述某一个n的规则是多少,eg

1:1

2:11(上一层的数字描述是 1个1)

3:21(上一层的数字描述是 2个1)

4:1211(上一层的数字描述是 1个2、1个1)

...

解题思路:为了获得n的结果我们需要先知道n-1的结果是多少,典型递归。

    public String countAndSay(int n) {
        if (n == 1) {
            return "1";
        }
        String str = countAndSay(n - 1);
        char[] chars = str.toCharArray();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            char now = chars[i];
            int count = 1;
            while (i + 1 < chars.length && chars[i + 1] == now) {
                i++;
                count++;
            }
            builder.append(count).append(now);
        }
        return builder.toString();
    }

猜你喜欢

转载自blog.csdn.net/TRUE_LOVE1314/article/details/82829508