Implement Set using Array.

2024-09-04 15:32
文章标签 set using implement array

本文主要是介绍Implement Set using Array.,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

参考链接:http://faculty.washington.edu/moishe/javademos/ch03%20Code/jss2/ArraySet.java

被Pivotal的面试官给问到了,trick的地方在于remove的那一块,要把最后的元素跟自己remove的元素进行互换,然后count--;还有,自动扩容那块,构造函数需要两个,一个默认的,一个是可以限定side的。然后扩容的时候,阔完了,需要把larger 给contents。这都是容易错的地方,我当时就忘记赋值了。两个地方没有做好,然后就挂掉了。

//********************************************************************
//  ArraySet.java       Author: Lewis/Chase
//
//  Represents an array implementation of a set.
//********************************************************************package jss2;
import jss2.exceptions.*;
import java.util.*;public class ArraySet<T> implements SetADT<T>
{private static Random rand = new Random();private final int DEFAULT_CAPACITY = 100;private final int NOT_FOUND = -1;private int count;  // the current number of elements in the set private T[] contents; //-----------------------------------------------------------------//  Creates an empty set using the default capacity.//-----------------------------------------------------------------public ArraySet(){count = 0;contents = (T[])(new Object[DEFAULT_CAPACITY]);}//-----------------------------------------------------------------//  Creates an empty set using the specified capacity.//-----------------------------------------------------------------public ArraySet (int initialCapacity){count = 0;contents = (T[])(new Object[initialCapacity]);}//-----------------------------------------------------------------//  Adds the specified element to the set if it's not already//  present. Expands the capacity of the set array if necessary.//-----------------------------------------------------------------public void add (T element){if (!(contains(element))){if (size() == contents.length) expandCapacity();contents[count] = element;count++;}}//-----------------------------------------------------------------//  Adds the contents of the parameter to this set.//-----------------------------------------------------------------public void addAll (SetADT<T> set){Iterator<T> scan = set.iterator();while (scan.hasNext())add (scan.next());}//-----------------------------------------------------------------//  Removes a random element from the set and returns it. Throws//  an EmptySetException if the set is empty.//-----------------------------------------------------------------public T removeRandom() throws EmptySetException{if (isEmpty())throw new EmptySetException();int choice = rand.nextInt(count);T result = contents[choice];contents[choice] = contents[count-1];  // fill the gapcontents[count-1] = null;count--;return result;}//-----------------------------------------------------------------//  Removes the specified element from the set and returns it.//  Throws an EmptySetException if the set is empty and a//  NoSuchElementException if the target is not in the set.//-----------------------------------------------------------------public T remove (T target) throws EmptySetException,NoSuchElementException{int search = NOT_FOUND;if (isEmpty())throw new EmptySetException();for (int index=0; index < count && search == NOT_FOUND; index++)if (contents[index].equals(target))search = index;if (search == NOT_FOUND)throw new NoSuchElementException();T result = contents[search];contents[search] = contents[count-1];contents[count-1] = null;count--;return result;}//-----------------------------------------------------------------//  Returns a new set that is the union of this set and the//  parameter.//-----------------------------------------------------------------public SetADT<T> union (SetADT<T> set){ArraySet<T> both = new ArraySet<T>();for (int index = 0; index < count; index++)both.add (contents[index]);Iterator<T> scan = set.iterator();while (scan.hasNext())both.add (scan.next());return both;}//-----------------------------------------------------------------//  Returns true if this set contains the specified target//  element.//-----------------------------------------------------------------public boolean contains (T target){int search = NOT_FOUND;for (int index=0; index < count && search == NOT_FOUND; index++)if (contents[index].equals(target))search = index;return (search != NOT_FOUND);}//-----------------------------------------------------------------//  Returns true if this set contains exactly the same elements//  as the parameter.//-----------------------------------------------------------------public boolean equals (SetADT<T> set){boolean result = false;ArraySet<T> temp1 = new ArraySet<T>();ArraySet<T> temp2 = new ArraySet<T>();T obj;if (size() == set.size()){ temp1.addAll(this);temp2.addAll(set);Iterator<T> scan = set.iterator();while (scan.hasNext()){obj = scan.next();   if (temp1.contains(obj)){temp1.remove(obj);temp2.remove(obj);}}result = (temp1.isEmpty() && temp2.isEmpty());}return result;}//-----------------------------------------------------------------//  Returns true if this set is empty and false otherwise. //-----------------------------------------------------------------public boolean isEmpty(){return (count == 0);}//-----------------------------------------------------------------//  Returns the number of elements currently in this set.//-----------------------------------------------------------------public int size(){return count;}//-----------------------------------------------------------------//  Returns an iterator for the elements currently in this set.//-----------------------------------------------------------------public Iterator<T> iterator(){return new ArrayIterator<T> (contents, count);}//-----------------------------------------------------------------//  Returns a string representation of this set. //-----------------------------------------------------------------public String toString(){String result = "";for (int index=0; index < count; index++) result = result + contents[index].toString() + "\n";return result;}//-----------------------------------------------------------------//  Creates a new array to store the contents of the set with//  twice the capacity of the old one.//-----------------------------------------------------------------private void expandCapacity(){T[] larger = (T[])(new Object[contents.length*2]);for (int index=0; index < contents.length; index++)larger[index] = contents[index];contents = larger;}
}


这篇关于Implement Set using Array.的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1136347

相关文章

poj 3050 dfs + set的妙用

题意: 给一个5x5的矩阵,求由多少个由连续6个元素组成的不一样的字符的个数。 解析: dfs + set去重搞定。 代码: #include <iostream>#include <cstdio>#include <set>#include <cstdlib>#include <algorithm>#include <cstring>#include <cm

Collection List Set Map的区别和联系

Collection List Set Map的区别和联系 这些都代表了Java中的集合,这里主要从其元素是否有序,是否可重复来进行区别记忆,以便恰当地使用,当然还存在同步方面的差异,见上一篇相关文章。 有序否 允许元素重复否 Collection 否 是 List 是 是 Set AbstractSet 否

论文翻译:ICLR-2024 PROVING TEST SET CONTAMINATION IN BLACK BOX LANGUAGE MODELS

PROVING TEST SET CONTAMINATION IN BLACK BOX LANGUAGE MODELS https://openreview.net/forum?id=KS8mIvetg2 验证测试集污染在黑盒语言模型中 文章目录 验证测试集污染在黑盒语言模型中摘要1 引言 摘要 大型语言模型是在大量互联网数据上训练的,这引发了人们的担忧和猜测,即它们可能已

多路转接之select(fd_set介绍,参数详细介绍),实现非阻塞式网络通信

目录 多路转接之select 引入 介绍 fd_set 函数原型 nfds readfds / writefds / exceptfds readfds  总结  fd_set操作接口  timeout timevalue 结构体 传入值 返回值 代码 注意点 -- 调用函数 select的参数填充  获取新连接 注意点 -- 通信时的调用函数 添加新fd到

Android set Tag, findViewWithTag使用

设置了tag为“principal”的view ImageView principal = (ImageView) findViewById(R.id.imagen_home_0);principal.setTag("principal"); 在其它地方获取,获取已经设置了tag为“principal”的view LayoutInflater inflater = LayoutInflate

C++ STL关联容器Set与集合论入门

1. 简介 Set(集合)属于关联式容器,也是STL中最实用的容器,关联式容器依据特定的排序准则,自动为其元素排序。Set集合的底层使用一颗红黑树,其属于一种非线性的数据结构,每一次插入数据都会自动进行排序,注意,不是需要排序时再排序,而是每一次插入数据的时候其都会自动进行排序。因此,Set中的元素总是顺序的。 Set的性质有:数据自动进行排序且数据唯一,是一种集合元素,允许进行数学上的集合相

Eclipse或MyEclipse中Java Working Set管理项目

随着学习JAVA的时间的越来越久,项目也越来越多,Eclipse或MyEclipse界面中显示一堆! 每次工作使用到的项目肯定不会太多...... 每次从这么大数量的工程当中找到自己要使用的, 必须大规模的滚动滚动条...... 图片一   Project Explorer中:    图片二:Package Explorer中: 这样就好找很多了,分类放!

【uva】11536-Smallest Sub-Array(区间移动问题)

一个区间移动的问题,1A了,感觉没什么好说的。。 13975926 11536 Smallest Sub-Array Accepted C++ 0.809 2014-08-01 11:00:20 #include<cstdio>#include<cstring>#include<iostream>using namespace std;#define INF 1 << 30

STL set整理

#include<set>#include<cstdio>#include<iterator>#include<iostream>#include<algorithm>using namespace std;//set 集合的操作//multisetset<int>Set1;set<int>Set2;set<int>Set3;/*begin() 返回指向第一个元素的迭代器

解决PHP Warning: strftime(): It is not safe to rely on the system's timezone set

当运行一些程序时,在httpd日志中会有如下警告日志: PHP Warning:  strftime(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set(