Java数据结构实现数组(配套习题)

数据结构

数组

  • 一组相同数据类型的集合

特点

  1. 数组在内存中是连续分配的
  2. 创建时要指明数组的大小
  3. 数组名代表首地址,索引从0开始,到数组的长度-1
  4. 数组一旦创建好,大小不可以改变
  5. 使用索引
    1. 获取索引位置的值 arr[index]
    2. 修改 arr[index] = val
    3. 删除 (假删除)
    4. 遍历,将数组中的元素,依次打印出来

使用Java实现更高级的数组

package Arrays;

import java.util.Random;

public class MyArr<T> {

    private int capacity = 0;
    private int size = 0;
    private T[] arr;

    public MyArr(int capacity) {
        if (capacity < 0) this.capacity = 10; //if no right input, we will initial capacity 10
        this.capacity = capacity;
        this.arr = (T[]) new Object[capacity];
    }

    public int getCapacity() {
        return capacity;
    }

    public int getSize() {
        return size;
    }

    public T[] setCapacity(int capacity) {
        if (capacity < 0) {
            throw new RuntimeException("扩大小异常");
        }
        this.capacity = capacity;
        T[] newNum = (T[]) new Object[capacity];
        for (int i = 0; i < this.size; ++i) {
            newNum[i] = this.arr[i];
        }
        return newNum;
    }

    //增加元素
    public void add(T val) {
        if (this.size >= this.capacity) {
            this.arr = setCapacity(2 * this.capacity);
        }
        this.arr[this.size++] = val;
    }

    //删除元素
    public boolean removeByIndex(int index) {
        if (index < 0 || index > this.capacity) {
            throw new RuntimeException("数组越界");
        }
        for (int i = index; i < size - 1; ++i) {
            arr[i] = arr[i + 1];
        }
        size--;
        if (size < this.capacity / 4 && this.capacity > 4) {
            arr = setCapacity(this.capacity / 4);
        }
        return true;
    }

    //修改位置元素
    public void modify(int index, T val) {
        if (index < 0 || index > size - 1) {
            throw new RuntimeException("数组越界");
        }
        arr[index] = val;
    }

    //获取某元素位置
    public int locateVal(T val) {
        for (int i = 0; i < size; ++i) {
            if (arr[i] == val) {
                return i;//return index
            }
        }
        // if no find return -1
        return -1;
    }
    //打印元素


    @Override
    public String toString() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append('[');
        for (int i = 0; i < this.size - 1; ++i) {
            stringBuffer.append(arr[i] + ",");
        }
        if(size>0) stringBuffer.append(arr[size - 1]);
        stringBuffer.append(']');
        return stringBuffer.toString();
    }

}

对应习题

26. 删除有序数组中的重复项

class Solution {
    public int removeDuplicates(int[] nums) {
    /*    TreeSet<Integer> set = new TreeSet<>();
        for(int i=0;i<nums.length;i++){
            set.add(nums[i]);
        }
        Iterator<Integer> iterator = set.iterator();
        int temp=0;
        while(iterator.hasNext()){
            nums[temp] = iterator.next();
            temp++;
        }

        return set.size();
        */
        //使用双指针,优化
        /*
        int p=0;
        int q = 1;
        if(nums==null||nums.length==0)return 0;
        while(q<nums.length){
            if(nums[p]!=nums[q]){
                nums[p+1]=nums[q];
                p++;
            }
            q++;
        }
        return p+1;
        */
        //当数组根本不存在重复元素时,则上面的方法每次依然会进行重复的复制,显然这是没有必要的

        //再次优化
        int p=0;
        int q = 1;
        if(nums==null||nums.length==0)return 0;
        while(q<nums.length){
            if(nums[p]!=nums[q]){
                if(q-p>1)nums[p+1]=nums[q];//判断
                p++;
            }
            q++;
        }
        return p+1;
    }
}

image-20240117203537713

1. 两数之和

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] numsSum = new int[2];
            HashMap<Integer,Integer> hashMap = new HashMap<>();
            for(int i=0;i<nums.length;++i){
                  if(hashMap.containsKey(target - nums[i])){
                    return new int[]{i, hashMap.get(target - nums[i])};
                }
                hashMap.put(nums[i],i);
            }
            return null;
            // int[] numsSum = new int[2];
            // if(nums==null||nums.length<2)return numsSum;
            // int len = nums.length;
            // HashMap<Integer,Integer> hashMap = new HashMap<>();
            // for(int i=0;i<nums.length;++i){
            //     hashMap.put(nums[i],i);
            // }
            // int temp=0;
            // for(int i=0;i<nums.length;++i){
            //     temp = target - nums[i];
            //     if(hashMap.containsKey(temp)&&hashMap.get(temp)!=i){
            //         numsSum = new int[]{i, hashMap.get(temp)};
            //     }
            // }
            // return numsSum;
            
    }    

}

image-20240117203448318

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        lens = len(nums)
        dic_num = {}
        for i in range(0,lens):
            if(target-nums[i]) in dic_num:
                  return [i,dic_num.get(target-nums[i])]
            dic_num[nums[i]] = i

        return []
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

崔渭阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值