秋招-数据结构-数组篇

秋招-数据结构-数组篇

介绍

数组是一个固定长度的存储相同数据类型的数据结构,数组中的元素被存储在一段连续的内存空间中。它是最简单的数据结构之一,大多数现代编程语言都内置数组支持。

技巧

在处理数组相关问题时,双指针技巧是经常用到的,双指针技巧主要分为两类:左右指针和快慢指针。

所谓左右指针,就是两个指针相向而行或者相背而行,主要服务于一个中心点;而所谓快慢指针,就是两个指针同向而行,一快一慢,主要服务于一段长度。

例题

283. 移动零

image-20220803231912311

class Solution {
    
    
    public void moveZeroes(int[] nums) {
    
    
        int slow,fast;
        slow = fast = 0;
        int con = 0;
        while(fast<nums.length){
    
    
            if(nums[fast]!=0){
    
    
                nums[slow] = nums[fast];
                slow++;
            }else{
    
    
               con ++;
            }
            fast++;
        }

        while(con>0){
    
    
            nums[nums.length-con] = 0;
            con--;
        }
        

    }
}

167. 两数之和 II - 输入有序数组

image-20220803215505418

class Solution {
    
    
    public int[] twoSum(int[] numbers, int target) {
    
    
        int high = numbers.length-1;
        int low = 0;
        while(true){
    
    
            if(numbers[high]+numbers[low]>target){
    
    
                high--;
            }
            else if(numbers[high]+numbers[low]<target){
    
    
                low++;
            }
            else{
    
    
                break;
            }
                
        }
        return new int[]{
    
    low+1,high+1};

    }
}

5. 最长回文子串

class Solution {
    
    
    public String longestPalindrome(String s) {
    
    
        String res = "";
        int len = s.length();
        char[] chars = s.toCharArray();
        for (int i = 0; i < len; i++) {
    
    
            String s1 = findMax(s,i,i);
            String s2 = findMax(s,i,i+1);
            res = res.length() > s1.length() ? res : s1;
            res = res.length() > s2.length() ? res : s2;
        }
        return res;

    }

    private String findMax(String s, int left, int right) {
    
    
        while (left>=0&&right<=s.length()-1&&
            s.charAt(left)==s.charAt(right)){
    
    
            left--;
            right++;
        }
        return s.substring(left+1,right);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_50665031/article/details/126166921