LeetCode算法题1-10

1.Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解决:

问题是要从数组中找到两个数据,使得两数之和等于目标值,输出该两数的下标(从0开始)。显而易见,这里最简单的是O(n^2)的时间复杂度的解决办法。

public static int[] twoSum(int[] nums, int target) {
    int[] answer = new int[2];
    A:for (int i = 0; i < nums.length; ++i){
        answer[0] = i;
        int b = target - nums[i];
        for (int j = i + 1; j < nums.length; ++j){
            if (nums[j] == b){
                answer[1] = j;
                break A;
            }
        }
    }
    return answer;
}
考虑O(n)的算法,可以使用map使得查找的复杂度降为O(1)。

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

2.You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

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

        //把相加后的结果存放于链表1,pre1是用于最后有进位时在其后new新结点  
        ListNode ret = l1;  
        ListNode pre1 = new ListNode(0);  
        pre1.next = l1;  

        int flag = 0;  
        while (l1 != null && l2 != null) {  
            l1.val = l1.val + l2.val + flag;  
            flag = l1.val / 10;  
            l1.val = l1.val % 10;  
            pre1 = l1;  
            l1 = l1.next;  
            l2 = l2.next;  
        }  

        //如果链表2有剩余,接到链表1的后面  
        if (l2 != null) {  
            pre1.next = l2;  
            l1 = l2;  
        }  

        while (l1 != null) {  
            l1.val += flag;  
            flag = l1.val / 10;  
            l1.val = l1.val % 10;  
            pre1 = l1;  
            l1 = l1.next;  
        }  

        if (flag > 0) {  
            ListNode node = new ListNode(1);  
            pre1.next = node;  
        }  

        return ret;  
    }  
}

3.Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

    //时间复杂度o(n*n)
    public   int lengthOfLongestSubstring(String s) {
        if(null==s||s.length()==0){
            return  0;
        }
        int max=0;
        for(int i=0;i<s.length();i++){
            StringBuilder sb=new StringBuilder();
            for(int j=i;j<s.length();j++){
                if(sb.toString().contains(String.valueOf(s.charAt(j)))){
                    break;
                }else {
                    sb.append(s.charAt(j));
                    if(sb.length()>max){
                        max=sb.length();
                    }
                }
            }
        }
        return  max;
    }
    //时间复杂度o(n)
        public   int lengthOfLongestSubstring(String s) {
        if(null==s||s.length()==0){
            return  0;
        }
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max=0;
        for (int i=0, j=0; i<s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
        }
        return max;
    }
}

4.There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5

public double findMedianSortedArrays(int[] A, int[] B) {
        int m = A.length, n = B.length;
        int l = (m + n + 1) / 2;
        int r = (m + n + 2) / 2;
        return (getkth(A, 0, B, 0, l) + getkth(A, 0, B, 0, r)) / 2.0;
    }

public double getkth(int[] A, int aStart, int[] B, int bStart, int k) {
    if (aStart > A.length - 1) return B[bStart + k - 1];            
    if (bStart > B.length - 1) return A[aStart + k - 1];                
    if (k == 1) return Math.min(A[aStart], B[bStart]);

    int aMid = Integer.MAX_VALUE, bMid = Integer.MAX_VALUE;
    if (aStart + k/2 - 1 < A.length) aMid = A[aStart + k/2 - 1]; 
    if (bStart + k/2 - 1 < B.length) bMid = B[bStart + k/2 - 1];        

    if (aMid < bMid) 
        return getkth(A, aStart + k/2, B, bStart,       k - k/2);// Check: aRight + bLeft 
    else 
        return getkth(A, aStart,       B, bStart + k/2, k - k/2);// Check: bRight + aLeft
}
  1. Longest Palindromic Substring
/**
     *
     * @param  Input: "babad"     Output: "bab"   Note: "aba" is also a valid answer.
     * @return String
     * 思想:中心扩展法
     */
    private  int lo;
    private int maxLen;
    public String longestPalindrome(String s) {
        int len=s.length();
        if(len<2){
            return  s;
        }
        for(int i=0;i<len-1;i++){
            extendPalindrome(s, i, i);//奇数扩展
            extendPalindrome(s,i,i+1);//偶数扩展
        }
        return  s.substring(lo,maxLen+lo);
    }
    public void extendPalindrome(String s,int j,int k){
        while (j>=0&&k<s.length()&&s.charAt(j)==s.charAt(k)){
            j--;
            k++;
        }
        if(maxLen<k-j-1){
            lo=j+1;
            maxLen=k-j-1;
        }
    }
  1. ZigZag Conversion
   /**
     * 通过创建numRows 个StringBuffer 进行拼接
     * @param  6.ZigZag Conversion   convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR"
     * @param s ,numRows
     * @return string
     */
    public String convert(String s, int numRows) {
        char[] c=s.toCharArray();
        int len=s.length();
        StringBuilder[] sb=new StringBuilder[numRows];
        for(int i=0;i<numRows;i++){
            sb[i]=new StringBuilder();
        }
        int i=0;
        while (i<len){
            for(int idx=0;idx<numRows&&i<len;idx++){
                sb[idx].append(c[i++]);
            }//垂直方向
            for(int idx=numRows-2;idx>=1&&i<len;idx--){
                sb[idx].append(c[i++]);
            }//斜线方向
        }
        for(int idx=1;idx<sb.length;idx++){
            sb[0].append(sb[idx]);
        }
        return  sb[0].toString();
    }
}

7.Reverse Integer
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

    public int reverse(int x) {
        int result=0;
        while (x!=0){
            int tail=x%10;
            int newResult=result*10+tail;
            if((newResult-tail)/10!=result){
                return 0;
            }
            result=newResult;
            x=x/10;
        }
        return  result;
    }

8.String to Integer (atoi)
Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

    /**
     * String to Integer (atoi)
     * @param str
     * @return int
     */
    public int myAtoi(String str) {
        if(str==null||str.length()==0){
            return  0;
        }
        str=str.trim();
        char firstChar=str.charAt(0);
        int sign=1;
        int start=0;
        int len=str.length();
        long sum=0;
        if(firstChar=='+'){
            sign=1;
            start++;
        }else  if(firstChar=='-'){
            sign=-1;
            start++;
        }
        for(int i=start;i<len;i++){
            if(!Character.isDigit(str.charAt(i))){
                return (int)sum*sign;
            }
            sum=sum*10+str.charAt(i)-'0';
            if (sign == 1 && sum > Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            if (sign == -1 && (-1) * sum < Integer.MIN_VALUE)
                return Integer.MIN_VALUE;
        }
        return (int) sum * sign;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智慧校园整体解决方案是响应国家教育信息化政策,结合教育改革和技术创新的产物。该方案以物联网、大数据、人工智能和移动互联技术为基础,旨在打造一个安全、高效、互动且环保的教育环境。方案强调从数字化校园向智慧校园的转变,通过自动数据采集、智能分析和按需服务,实现校园业务的智能化管理。 方案的总体设计原则包括应用至上、分层设计和互联互通,确保系统能够满足不同用户角色的需求,并实现数据和资源的整合与共享。框架设计涵盖了校园安全、管理、教学、环境等多个方面,构建了一个全面的校园应用生态系统。这包括智慧安全系统、校园身份识别、智能排课及选课系统、智慧学习系统、精品录播教室方案等,以支持个性化学习和教学评估。 建设内容突出了智慧安全和智慧管理的重要性。智慧安全管理通过分布式录播系统和紧急预案一键启动功能,增强校园安全预警和事件响应能力。智慧管理系统则利用物联网技术,实现人员和设备的智能管理,提高校园运营效率。 智慧教学部分,方案提供了智慧学习系统和精品录播教室方案,支持专业级学习硬件和智能化网络管理,促进个性化学习和教学资源的高效利用。同时,教学质量评估中心和资源应用平台的建设,旨在提升教学评估的科学性和教育资源的共享性。 智慧环境建设则侧重于基于物联网的设备管理,通过智慧教室管理系统实现教室环境的智能控制和能效管理,打造绿色、节能的校园环境。电子班牌和校园信息发布系统的建设,将作为智慧校园的核心和入口,提供教务、一卡通、图书馆等系统的集成信息。 总体而言,智慧校园整体解决方案通过集成先进技术,不仅提升了校园的信息化水平,而且优化了教学和管理流程,为学生、教师和家长提供了更加便捷、个性化的教育体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值