Java集操作

1.集内部不存在相同的元素

对于一个字符串,请设计一个高效算法,找到第一次重复出现的字符。
给定一个字符串(不一定全为字母)A及它的长度n。请返回第一个重复出现的字符。保证字符串中有重复字符,字符串的长度小于等于500。
测试样例:
“qywyer23tdd”,11
返回:y

import java.util.*;
public class FirstRepeat {
	public static char findFirstRepeat(String A, int n) {
	
	char[] a=A.toCharArray();
	HashSet hs=new HashSet<>();
	for(int i=0; i<n;i++) 
	{
		if (!hs.add(a[i])) //在向集内部添加元素时会检查是否含有对应元素
		{
			return a[i];
		}
	}
	return 0;
	}
 
	public static void main(String[] args)
	{
		System.out.println(findFirstRepeat("qywyer23tdd",11));
	}
}

(转载于https://blog.csdn.net/tingzhiyi/article/details/52152487)

2.如果需要通过foreach方法遍历来删除集中的元素需要新建一个集合来作为遍历的度

创建一个容量为20类型为Integer的集合并去除其中大于10的元素

public class Solution {
    public static HashSet<Integer> createSet() {
        // 在此编写你的代码
        HashSet<Integer> a=new HashSet<>();
        for(int i=0;i<20;i++){
            a.add(i);
        }
        return a;
    }

    public static HashSet<Integer> removeAllNumbersGreaterThan10(HashSet<Integer> set) {
        HashSet<Integer> copy = new HashSet<>(set);
        for (Integer n : copy) {
            if (n > 10) {
                set.remove(n);
            }
        }
        return set;
    }

    public static void main(String[] args) {
        for(Integer n :removeAllNumbersGreaterThan10(createSet())){
            System.out.println(n);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值