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;
    }

35. Search Insert Position

题目要求:有序数组中查找n或返回n应该在的位置

结题思路:

1.扫一遍

public int searchInsert(int[] nums, int target) {
        if (nums == null) {
            return 0;
        }
        for (int i = 0 ; i < nums.length; i++) {
            if (nums[i] >= target) {
                return i;
            }
        }
        return nums.length;
    }

2.二分(有待优化)

 if (nums == null || nums.length == 0) {
            return 0;
        }

        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int middle = (start + end) / 2;
            if (nums[middle] < target) {
                start = middle + 1;
            } else if (nums[middle] > target) {
                end = middle - 1;
            } else {
                return middle;
            }
        }
        if (end < 0) {
            return 0;
        } else if (start >= nums.length) {
            return nums.length;
        } else if (target < nums[end]) {
            return end;
        } else if (target < nums[start]) {
            return start;
        } else {
            return start + 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();
    }

53. Maximum Subarray

题目要求:有序数组中求其子数组且子数组的数字和最大。

解题思路:

1.输入数组 A[1,2,3,4,...,n]

对任意i和任意j(最优解数组的最大下标)而言  A[1,2,3,4,...,i] 范围内的最优解为B(i,j) 

则 若i=j, B(i+1,j) =  max((B(i,j) + A[i+1]),A[i+1]) = B(i+1,j) 或B(i+1,j+1)

i!=j时 B(i+1,j) = max(B(i,j),A[i+1]) 

简单的说就是从数组较小的一段向较大的一端扫描,求当前最优解和sum值

public int maxSubArray(int[] nums) {
        int currentMax = nums[0];
        int sum = nums[0];
        for (int i = 1; i < nums.length; i++) {
            sum = Math.max(sum + nums[i], nums[i]);
            currentMax = Math.max(currentMax, sum);
        }
        return currentMax;
    }

2.用分治实现1

58. Length of Last Word

题目要求:空格分割的String中找最后一个单词的长度

解题思路:转成char[],从后向前扫一遍。当然也可以用java自带的API

public int lengthOfLastWord(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        String[] strings = s.split("\\s+");

        return strings.length == 0 ? 0 :strings[strings.length - 1].length();
    }
public int lengthOfLastWord(String s) {
        return s.trim().length() - s.trim().lastIndexOf(" ") - 1;
    }

66. Plus One

题目要求:给一个int[] ,这个数组代表一个数字,eg [1,2,3] = 123, 之后将这个数字+1返回解析的数组 即返回[1,2,4]

解题思路:最后一位+1 注意下别溢出

public int[] plusOne(int[] digits) {
        boolean carry = false;
        for (int i = digits.length - 1; i >= 0; i--) {
            if (digits[i] < 9) {
                digits[i]++;
                carry = false;
                break;
            } else {
                digits[i] = 0;
                carry = true;
            }
        }
        if (!carry) {
            return digits;
        } else {
            int[] res = new int[digits.length + 1];
            res[0] = 1;
            for(int i = 1; i < res.length; i++) {
                res[i] = digits[i - 1];
            }
            return res;
        }
    }

67. Add Binary

题目要求:二进制字符串加法

解题思路:从低位向高位加过来,注意下首位不要溢出即可

    public String addBinary(String a, String b) {
        char[] aChars = a.toCharArray();
        char[] bChars = b.toCharArray();
        char[] sum = new char[aChars.length >= bChars.length ? aChars.length : bChars.length];
        int i, j, l;
        int k = 0;
        for (i = aChars.length - 1, j = bChars.length - 1, l = sum.length - 1; i >= 0 && j >= 0 && l >= 0; i--, j--, l--) {
            switch (Integer.valueOf(aChars[i]) + Integer.valueOf(bChars[j]) + k - 96) {
                case 0:
                    sum[l] = '0';
                    k = 0;
                    break;
                case 1:
                    sum[l] = '1';
                    k = 0;
                    break;
                case 2:
                    sum[l] = '0';
                    k = 1;
                    break;
                case 3:
                    sum[l] = '1';
                    k = 1;
                    break;
                default:
                    break;
            }
        }
        while (i >= 0) {
            switch (Integer.valueOf(aChars[i]) + k -48) {
                case 0:
                    sum[l] = '0';
                    k = 0;
                    break;
                case 1:
                    sum[l] = '1';
                    k = 0;
                    break;
                case 2:
                    sum[l] = '0';
                    k = 1;
                    break;
                default:
                    break;
            }
            l--;
            i--;
        }
        while (j >= 0) {
            switch (Integer.valueOf(bChars[j]) + k -48) {
                case 0:
                    sum[l] = '0';
                    k = 0;
                    break;
                case 1:
                    sum[l] = '1';
                    k = 0;
                    break;
                case 2:
                    sum[l] = '0';
                    k = 1;
                    break;
                default:
                    break;
            }
            j--;
            l--;
        }
        if (k == 0) {
            return String.valueOf(sum);
        } else {
            return "1" + String.valueOf(sum);
        }
    }

 

69.Sqrt(x)

给X开平方,直接查找就行,二分提高效率

public int mySqrt(int x) {
        if (x == 0) {
            return 0;
        } else if (x < 4) {
            return 1;
        } else if (x == 4) {
            return 2;
        }
        long start = 1;
        long end = x/2;
        long middle = -1;
        while (start <= end) {
            middle = (start + end) /2 ;
            long  middleValue = middle * middle;
            if (middleValue == x) {
                return  (int)middle;
            } else if (middleValue < x) {
                start = middle + 1;
            } else {
                end = middle - 1;
            }

        }
        if (middle * middle > x) {
            return (int)middle -1;
        } else {
            return (int)middle;
        }
    }

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值