java从键盘中输入一个不定长的数组

从键盘中输入一个不定长的数组,因为在某些题目中,给出的案例中的数组大小可能都不一致,这里我们用LeetCode上一一道简单题来举例:「两数之和」

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]


示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

代码如下:

import java.util.Arrays;
import java.util.Scanner;

public class LeetCode {
    public  int[] twoSum(int[] nums, int target) {
        for (int i = 0; i <nums.length ; i++) {
            for (int j = i+1; j < nums.length ; j++) {
                if(nums[i]+nums[j]==target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String[] nums=null;
        nums = sc.nextLine().split(" ");
        int[] num=new int[nums.length];
        for(int i=0;i<num.length;i++){
            num[i]=Integer.parseInt(nums[i]);
        }
        int target=sc.nextInt();

        LeetCode le=new LeetCode();
        System.out.println(Arrays.toString(le.twoSum(num, target)));
    }
}

主函数我们可以这样写,就可以实现从键盘中输入不定长的数组啦

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我理解了您的问题。以下是一个示例代码,实现了您的要求: ```c++ #include <iostream> #include <cstring> using namespace std; class mystring { private: char* str; int len; public: mystring() { str = nullptr; len = 0; } friend istream& operator>>(istream& is, mystring& s) { // 动态分配内存 char c; int i = 0; while (is.get(c)) { if (c == '\n') { break; } char* temp = new char[i + 1]; if (i > 0) { strcpy(temp, s.str); delete[] s.str; } temp[i] = c; s.str = temp; s.str[i + 1] = '\0'; i++; } s.len = i; return is; } friend ostream& operator<<(ostream& os, const mystring& s) { os << s.str; return os; } }; int main() { mystring s; cin >> s; cout << s << endl; return 0; } ``` 在这个示例代码,我们定义了一个名为 `mystring` 的类,其包含一个字符指针 `str` 和一个整数 `len`,用于存储输入的字符串和字符串长度。我们还定义了 `>>` 和 `<<` 运算符,以便能够对 `mystring` 类对象进行输入和输出。 在 `>>` 运算符,我们使用 `is.get(c)` 逐个读取字符,并检查是否到达了回车符。如果没有到达回车符,我们将字符存储到动态分配的内存,并将 `str` 指向该内存。如果已经存储了一些字符,我们将使用 `strcpy` 将旧字符串复制到新字符串,并释放旧内存。最后,我们将输入字符的数量存储到 `len` 。 在 `<<` 运算符,我们只需简单地输出 `str`。 最后,在 `main` 函数,我们创建一个 `mystring` 类对象 `s`,并使用 `cin >> s` 输入字符串,然后使用 `cout << s` 输出该字符串。 希望这个示例代码能够帮助您理解如何实现自定义的 mystring 类。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值